java.util.concurrent.ThreadPoolExecutor实现机制简介

java.util.concurrent.ThreadPoolExecutor实现机制简介

前言

最近面试的时候被问到『如何实现一个线程池』的问题。当时没回答上来。
今天看了一下JDK源码,大概了解了一下java.util.concurrent.ThreadPoolExecutor的实现方式,整理如下。

思路

根据javadoc中关于ThreadPoolExecutor类的描述可知。ThreadPoolExecutor的实现主要依靠两个数据结构:

  1. 线程池
  2. 任务队列

任务队列使用的数据结构比较容易想到,可以采用实现了java.util.concurrent.BlockingQueue接口的类。
线程池该怎么实现才能让线程池里的线程持续执行一个接一个的任务呢?

我们来看一下JDK里是怎么实现的吧。

线程池

public class ThreadPoolExecutor extends AbstractExecutorService {
   

    ...

    /**
     * Set containing all worker threads in pool. Accessed only when
     * holding mainLock.
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();

    ...    

    /**
     * The queue used for holding tasks and handing off to worker
     * threads.  We do not require that workQueue.poll() returning
     * null necessarily means that workQueue.isEmpty(), so rely
     * solely on isEmpty to see if the queue is empty (which we must
     * do for example when deciding whether to transition from
     * SHUTDOWN to TIDYING).  This accommodates special-purpose
     * queues such as DelayQueues for which poll() is allowed to
     * return null even if it may later return non-null when delays
     * expire.
     */
    private final BlockingQueue<Runnable> workQueue;

    ...

}

如代码中的注释所说,workers就是存放工作线程的线程池,就是一个简单的HashSet。那么,关键信息一定是藏在这个Worker类里了。

Worker类

private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
   

    ...

    /** Thread this worker is running in.  Null if factory fails. */</
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值