Java 创建线程池的方式

Java 创建线程池的方式

Java 创建线程池主要有两种方法,一种是通过 Executors 工厂类提供的方法,该类提供了4种不同的线程池;另一种是通过 ThreadPoolExecutor类进行自定义创建。

1、通过 Executors 工厂类提供的方法

1.1、newCachedThreadPool

创建一个可缓存的线程池,若线程数超过处理所需,缓存一段时间后会回收,若线程数不够,则新建线程。

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        int number = i;
        executorService.execute(() -> {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + number);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

运行效果:

image-20211012153250405

因为初始线程池没有线程,而线程不足会不断新建线程,所以线程名都是不一样的。

1.2、newFixedThreadPool

创建一个固定大小的线程池,可控制并发的线程数,超出的线程会在队列中等待。

ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
    int number = i;
    executorService.execute(() -> {
        System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

运行效果:

image-20211012153559224

因为线程池大小是固定的,这里设置的是3个线程,所以线程名只有3个。因为线程不足会进入队列等待线程空闲,所以日志间隔2秒输出。

1.3、newScheduledThreadPool

创建一个周期性的线程池,支持定时及周期性执行任务。

public static void main(String[] args) {
    ScheduledExecutorService  executorService = Executors.newScheduledThreadPool(3);
    System.out.println(LocalDateTime.now() + " " + "执行任务");
    for (int i = 0; i < 10; i++) {
        int number = i;
        executorService.schedule(() -> {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + number);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },3, TimeUnit.SECONDS);
    }
}

运行效果:

image-20211012155541924

因为设置了延迟3秒,所以提交后3秒才开始执行任务。因为这里设置核心线程数为3个,而线程不足会进入队列等待线程空闲,所以日志间隔2秒输出。

注意:这里用的是ScheduledExecutorService类的schedule()方法,不是ExecutorService类的execute()方法。

1.4、newSingleThreadExecutor

创建一个单线程的线程池,可保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

public static void main(String[] args) {
    ExecutorService  executorService = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 10; i++) {
        int number = i;
        executorService.execute(() -> {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + number);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

运行效果:

image-20211012155858560

因为只有一个线程,所以线程名均相同,且是每隔2秒按顺序输出的。

2、通过ThreadPoolExecutor类自定义(推荐)

ThreadPoolExecutor类提供了4种构造方法,可根据需要来自定义一个线程池。

image-20211012161434990

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    //省略
}

2.1、构造方法的七个参数

7个参数如下:

(1)corePoolSize:核心线程数,线程池中始终存活的线程数。

(2)maximumPoolSize: 最大线程数,线程池中允许的最大线程数。

(3)keepAliveTime: 存活时间,线程没有任务执行时最多保持多久时间会终止。

(4)unit: 单位,参数 keepAliveTime 的时间单位,7种可选。

参数 描述
TimeUnit.DAYS
TimeUnit.HOURS 小时
TimeUnit.MINUTES
TimeUnit.SECONDS
TimeUnit.MILLISECONDS 毫秒
TimeUnit.MICROSECONDS 微妙
TimeUnit.NANOSECONDS 纳秒

(5)workQueue: 一个阻塞队列,用来存储等待执行的任务,均为线程安全,7种可选。

参数 描述
ArrayBlockingQueue 一个由数组结构组成的有界阻塞队列。
LinkedBlockingQueue 一个由链表结构组成的有界阻塞队列。
SynchronousQueue 一个不存储元素的阻塞队列,即直接提交给线程不保持它们。
PriorityBlockingQueue 一个支持优先级排序的无界阻塞队列。
DelayQueue 一个使用优先级队列实现的无界阻塞队列,只有在延迟期满时才能从中提取元素。
LinkedTransferQueue 一个由链表结构组成的无界阻塞队列。与SynchronousQueue类似,还含有非阻塞方法。
LinkedBlockingDeque 一个由链表结构组成的双向阻塞队列。

较常用的是 LinkedBlockingQueue 和 Synchronous。线程池的排队策略与 BlockingQueue 有关。

(6)threadFactory: 线程工厂,主要用来创建线程,默及正常优先级、非守护线程。

(7)handler:拒绝策略,拒绝处理任务时的策略,4种可选,默认为 AbortPolicy。

参数 描述
AbortPolicy 拒绝并抛出异常。
CallerRunsPolicy 重试提交当前的任务,即再次调用运行该任务的execute()方法。
DiscardOldestPolicy 抛弃队列头部(最旧)的一个任务,并执行当前任务。
DiscardPolicy 抛弃当前任务。

2.2、线程池执行规则

线程池的执行规则如下:

(1)当线程数小于核心线程数时,创建线程。

(2)当线程数大于等于核心线程数,且任务队列未满时,将任务放入任务队列。

(3)当线程数大于等于核心线程数,且任务队列已满:

若线程数小于最大线程数,创建线程。

若线程数等于最大线程数,抛出异常,拒绝任务。

public static void main(String[] args) {
    ExecutorService executorService = new ThreadPoolExecutor(2, 10, 1, TimeUnit.MINUTES,
                                                             new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
    for (int i = 0; i < 10; i++) {
        int number = i;
        executorService.execute(() -> {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " " + number);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

运行效果:

image-20211012162705435

因为核心线程数为2,队列大小为5,存活时间1分钟,所以流程是第0-1号任务来时,陆续创建2个线程,然后第2-6号任务来时,因为无线程可用,均进入了队列等待,第7-9号任务来时,没有空闲线程,队列也满了,所以陆续又创建了3个线程。所以你会发现7-9号任务反而是先执行的。又因为各任务只需要2秒,而线程存活时间有1分钟,所以线程进行了复用,所以总共只创建了5个线程。

3、优劣比较

虽然看上去 Executors 类的封装,可以简化我们的使用,但事实上,阿里代码规范《阿里巴巴Java开发手册》中明确不建议使用 Executors 类提供的这4种方法

【强制】线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

Executors返回的线程池对象的弊端如下:

FixedThreadPool和SingleThreadPool:允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。

CachedThreadPool和ScheduledThreadPool:允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。

所以我们应该使用ThreadPoolExecutor类来创建线程池,根据自己需要的场景来创建一个合适的线程池。

参考资料https://www.cnblogs.com/pcheng/p/13540619.html

posted @ 2021-10-12 16:37  MyDistance  阅读(2244)  评论(0编辑  收藏  举报