Java并发编程之Executors类详解

2022-07-23,,,,

一、executors的理解

  • executors类属于java.util.concurrent包;
  • 线程池的创建分为两种方式:threadpoolexecutor 和 executors;
  • executors(静态executor工厂)用于创建线程池;
  • 工厂和工具方法executor , executorservice , scheduledexecutorservice , threadfactory和callable在此包中定义的类;

jdk1.8api中的解释如下:

 

二、executors类图结构

三、executors常用的方法

  • public static executorservice newfixedthreadpool(int nthreads) 一种线程数量固定的线程池,当线程处于空闲状态时,他们并不会被回收,除非线程池被关闭。当所有的线程都处于活动状态时,新的任务都会处于等待状态,直到有线程空闲出来。
  • public static executorservice newsinglethreadexecutor() 创建单个线程。它适用于需要保证顺序地执行各个任务;并且在任意时间点,不会有多个线程是活动的应用场景。
  • public static executorservice newcachedthreadpool() 创建一个根据需要创建新线程的线程池,但在可用时将重新使用以前构造的线程, 如果没有可用的线程,将创建一个新的线程并将其添加到该池中。 未使用六十秒的线程将被终止并从缓存中删除。
  • public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize) 创建一个线程池,可以调度命令在给定的延迟之后运行,或定期执行, 支持执行定时性或周期性任务。
  • public static executorservice newworkstealingpool(int parallelism) 创建一个维护足够的线程以支持给定的并行级别的线程池,并且可以使用多个队列来减少争用。 ( jdk1.8版本新增的方法 )

四、executors类中常用方法示例

1、newfixedthreadpool方法示例

代码

package com.xz.thread.executors;

import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

/**
 * @description: 
 * @author: xz
 * @create: 2021-06-16 21:33
 */
public class demo {
    public static void main(string[] args) {
        //创建数量固定的线程池,线程池数量为3
        executorservice fixedthreadpool = executors.newfixedthreadpool(3);
        for(int i=0;i<5;i++){
            fixedthreadpool.execute(new runnable() {
                @override
                public void run() {
                    system.out.println(thread.currentthread().getname());
                    try {
                        thread.sleep(500);
                        system.out.println("睡眠一秒");
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            });
        }

    }
}

输出结果如下图

结论:示例中创建了数量固定为3的线程,由输出结果截图可知,遍历次数为5次,当执行一轮(3次)后,停顿一秒钟,直到有线程空闲出来,才继续第4次执行。

2、newsinglethreadexecutor方法示例

代码

package com.xz.thread.executor;

import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

/**
 * @description:
 * @author: xz
 * @create: 2021-06-15 22:33
 */
public class demo {
    public static void main(string[] args) {
        //创建单个线程
        executorservice singlethreadpool = executors.newsinglethreadexecutor();
        for(int i=0;i<5;i++){
            singlethreadpool.execute(new runnable() {
                @override
                public void run() {
                    system.out.println(thread.currentthread().getname());
                    try {
                        thread.sleep(1000);
                        system.out.println("睡眠一秒");
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            });
        }

    }
}

输出结果如下图

结论:示例中创建了创建单个线程,每执行一次任务后,睡眠一秒,保证顺序地执行各个任务。

3、newcachedthreadpool方法 代码

package com.xz.thread.executor;

import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

/**
 * @description:
 * @author: xz
 * @create: 2021-06-15 22:33
 */
public class demo {
    public static void main(string[] args) {
        //创建带有缓存功能的线程池
        executorservice cachedthreadpool = executors.newcachedthreadpool();
        for(int i=0;i<5;i++){
            cachedthreadpool.execute(new runnable() {
                @override
                public void run() {
                    system.out.println(thread.currentthread().getname());
                    try {
                        thread.sleep(1000);
                        system.out.println("睡眠一秒");
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            });
        }

    }
}

输出结果如下图

结论:示例中根据需要创建带有缓存线程的线程池,并在可用时将重新使用以前构造的线程。

4、newscheduledthreadpool方法示例

代码

package com.xz.thread.executor;

import java.time.localdatetime;
import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.timeunit;

/**
 * @description:
 * @author: xz
 * @create: 2021-06-15 22:33
 */
public class demo {
    public static void main(string[] args) {
        //创建执行周期性任务的线程池
        scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool(3);
        /**
         * schedule(runnable command,long delay, timeunit unit)方法参数解析
         * command 表示执行任务命令
         * delay 表示从现在开始延迟执行的时间
         * unit  延时参数的时间单位
         */
        scheduledthreadpool.schedule(new runnable() {
            @override
            public void run() {
                system.out.println("scheduledthreadpool:"+localdatetime.now());
            }
        },1l, timeunit.minutes);
        system.out.println("当前时间:"+localdatetime.now());
    }
}

输出结果如下图

结论:示例中创建执行周期性或定时性任务的线程池,由输出结果可知,设置的1分钟后执行任务已经生效。

五、executors创建线程池原理

1、无论是创建何种类型线程池(newfixedthreadpool、newsinglethreadexecutor、newcachedthreadpool等等),均会调用threadpoolexecutor构造函数。

2、 threadpoolexecutor构造函数中的参数解析

  • corepoolsize 核心线程最大数量,通俗点来讲就是,线程池中常驻线程的最大数量
  • maximumpoolsize 线程池中运行最大线程数(包括核心线程和非核心线程)
  • keepalivetime 线程池中空闲线程(仅适用于非核心线程)所能存活的最长时间
  • unit 存活时间单位,与keepalivetime搭配使用
  • workqueue 存放任务的阻塞队列
  • handler 线程池饱和策略

到此这篇关于java并发编程之executors类详解的文章就介绍到这了,更多相关java executors类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java并发编程之Executors类详解.doc》

下载本文的Word格式文档,以方便收藏与打印。