Executor框架使用ThreadPoolExecutor

2020-07-08  本文已影响0人  zbsong

java线程池 - ThreadPoolExecutor

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

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

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的运行示意图

例子

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的运行示意图

例子

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是一个没有容量的阻塞队列,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并发编程的艺术》推荐大家阅读。

上一篇 下一篇

猜你喜欢

热点阅读