美文网首页
Executor框架使用ThreadPoolExecutor

Executor框架使用ThreadPoolExecutor

作者: zbsong | 来源:发表于2020-07-08 18:11 被阅读0次

java线程池 - ThreadPoolExecutor

ThreadPoolExecutor是Executor框架的主要成员,也是最核心的类,是线程池的实现类。

通过Executor框架的Executors工具类,可以创建3种类型的ThreadPoolExecutor,如下

  • FixedThreadPool:适用于需要限制当前线程数量的应用场景
  • SingleThreadExecutor:适用于需要保证顺序地执行各个任务且在任意时间点,不会有多个线程活动的应用场景
  • CachedThreadPool:适用于执行很多的短期异步任务

FixedThreadPool

可重用固定线程数的线程池

源码

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

FixedThreadPool的运行示意图

FixedThreadPool的运行示意图
  • 如果当前运行的线程数少于corePoolSize,则创建新的线程来执行任务。
  • 当前运行的线程数等于或者大于corePoolSize,将任务加入到LinkedBlockingQueue。
  • 任务执行完后会在循环中反复从LinkedBlockingQueue中获取任务来执行
    -因为使用的是无界队列,所以运行中的FixedThreadPool不会拒绝任务,maximumPoolSizekeepAliveTime都是无效参数。

例子

package com.sy.thread.example;

import java.util.concurrent.*;

/**
 * Description: thread
 *
 * @author songyu
 */
public class FixedThreadPoolTest {

    public static void main(String[] args) {
        //因为newFixedThreadPool创建的是使用的无界的队列,如果IDEA里面安装了阿里的java编码规范会提示:
        //FixedThreadPool和SingleThreadPool: 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM
        //可以换一种写法等同写法,如下
        //int nThreads = 1;
        //ExecutorService service = new ThreadPoolExecutor(nThreads,nThreads,0L, TimeUnit.MILLISECONDS,
        //        new LinkedBlockingQueue<Runnable>());
        ExecutorService service = Executors.newFixedThreadPool(1);
        for(int i = 0; i < 5; i++) {
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("第" + finalI +  "任务执行");
                }
            });
            service.execute(thread);
        }
    }
}

SingleThreadExecutor

使用单个工作线程

源码

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

SingleThreadExecutor的运行示意图

SingleThreadExecutor的运行示意图
  • 任务提交到线程池后,如果线程池中没有运行的线程,则创建新的线程来执行任务。
  • 如果线程中有一个运行的线程,则将任务加入到LinkedBlockingQueue
  • 任务执行完后会在循环中反复从LinkedBlockingQueue中获取任务来执行。

例子

package com.sy.thread.example;

import java.util.concurrent.*;

/**
 * Description: thread
 *
 * @author songyu
 */
public class SingleThreadExecutorTest {

    public static void main(String[] args) {
        //因为newSingleThreadExecutor创建的是使用的无界的队列,如果IDEA里面安装了阿里的java编码规范会提示:
        //FixedThreadPool和SingleThreadPool: 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM
        //可以换一种写法等同写法,如下
        //ExecutorService service = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
        ExecutorService service = Executors.newSingleThreadExecutor();
        for(int i = 0; i < 5; i++) {
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("第" + finalI +  "任务执行");
                }
            });
            service.execute(thread);
        }
    }
}

CachedThreadPool

根据需要创建新线程

源码

 public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }

CachedThreadPoolcorePoolSize设置成0,即corePool为空,maximumPoolSize被设置为Integer.MAX_VALUE,即maximumPool是无界的,keepAliveTime设置为60L,即CachedThreadPool中的空闲线程等待新任务的最长时间为60s,超过60s就会被终止。
CachedThreadPool使用的是没有容量的SynchronousQueue作为工作队列,而maximumPool也是无界的,所以,如果主线程提交任务的速度大于线程池中的线程处理速度,CachedThreadPool会不断创建新线程,在极端情况下会因为创建过多的线程而耗尽CPU和内存资源。

CachedThreadPool运行示意图

CachedThreadPool运行示意图
  • 首先执行SynchronousQueue.offer(Runnable task),如果当前maximumPool中的空闲线程正在执行SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS),那么主线程执行offer操作与空闲线程执行的poll操作配对成功,主线程把任务交给空闲线程执行(当初始maximumPool为空或者maximumPool中当前没有空闲线程时,将没有线程执行SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS),上述步骤将会失败,这个时候CachedThreadPool会创建一个新线程执行任务。
  • 新创建的线程将任务执行完毕后,会执行SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)让空闲的线程最多在SynchronousQueue中等待60s,如果60s内主线程提交了新任务,那么空线程将执行新任务,否则线程终止。

SynchronousQueue是一个没有容量的阻塞队列,CachedThreadPool使用SynchronousQueue把主线程提交的任务传递给空闲线程执行。

CachedThreadPool中任务传递示意图

CachedThreadPool中任务传递示意图

例子

package com.sy.thread.example;

import java.util.concurrent.*;

/**
 * Description: thread
 *
 * @author songyu
 */
public class CachedThreadPoolTest {
    public static void main(String[] args) {
        //因为CachedThreadPool允许的创建线程数量为Integer.MAX_VALUE,如果IDEA里面安装了阿里的java编码规范会提示:
        //CachedThreadPool: 允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM
        //可以换一种写法等同写法,如下
        //ExecutorService service = new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
        ExecutorService service = Executors.newCachedThreadPool();
        for(int i = 0; i < 5; i++) {
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("第" + finalI +  "任务执行");
                }
            });
            service.execute(thread);
        }
    }
}

参考书籍《java并发编程的艺术》推荐大家阅读。

相关文章

网友评论

      本文标题:Executor框架使用ThreadPoolExecutor

      本文链接:https://www.haomeiwen.com/subject/iayccktx.html