多线程与并发一些收藏

Java并发编程:线程池ThreadPoolExecutor

2020-12-01  本文已影响0人  singleZhang2010

为什么使用线程池?

工作原理

ThreadPoolExecutor 执行 execute()方法的流程图:


execute

ThreadPoolExecutor执行示意图:


ThreadPoolExecutor

这里主要分以下四种情况:

ThreadPoolExecutor中线程执行任务示意图:


image.png

线程池中的线程执行任务分两种情况,如下。

Executors框架最核心的类是ThreadPoolExecutor,它是线程池的实现类,四个构造函数源码如下:

   //一
    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler);
    }

   //二
    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler);
    }

 //三
    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler);
    }

 //四
    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        this.ctl = new AtomicInteger(ctlOf(-536870912, 0));
        this.mainLock = new ReentrantLock();
        this.workers = new HashSet();
        this.termination = this.mainLock.newCondition();
        if (corePoolSize >= 0 && maximumPoolSize > 0 && maximumPoolSize >= corePoolSize && keepAliveTime >= 0L) {
            if (workQueue != null && threadFactory != null && handler != null) {
                this.corePoolSize = corePoolSize;
                this.maximumPoolSize = maximumPoolSize;
                this.workQueue = workQueue;
                this.keepAliveTime = unit.toNanos(keepAliveTime);
                this.threadFactory = threadFactory;
                this.handler = handler;
            } else {
                throw new NullPointerException();
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

参数说明:

线程池的拒绝策略

拒绝策略提供顶级接口 RejectedExecutionHandler ,其中方法 rejectedExecution 即定制具体的拒绝策略的执行逻辑。

线程池默认的AbortPlolicy不够优雅,直接在程序中抛出RejectedExecutionException异常(因为是运行时异常,不强制catch),推荐以下几种策略:

Executors中常见四种线程池创建方法

※不过一般不提倡使用Executors创建线程池,而是直接使用ThreadPoolExecutor 的构造函数创建线程池,避免OOM异常。
最后提供一个自定义线程池单例类:

public final class GlobalThreadPool {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 30;
    /**
     * 最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 60;
    /**
     * 空闲线程的存活时间
     */
    private static final int KEEP_ALIVE_TIME = 1000;
    /**
     * 任务队列的大小
     */
    private static final int  BLOCKING_QUEUE_SIZE = 1000;

    private GlobalThreadPool() {
    }
    /**
     * 饿汉模式初始化
     */
    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(BLOCKING_QUEUE_SIZE),
            new ThreadFactoryBuilder().setNameFormat("global-thread-pool-%d").build(),
            //任务拒绝策略为由调用该线程处执行该任务
            new  ThreadPoolExecutor.CallerRunsPolicy());
    public static ThreadPoolExecutor getExecutor() {
        return EXECUTOR;
    }
}
上一篇下一篇

猜你喜欢

热点阅读