线程池与其底层源码简单分析

1、常用得四种线程池为newCachedThreadPool、newFixedThreadPool、newSingleThreadExecutor和newScheduledThreadPool 和不常用newSingleThreadScheduledExecutor 、newWorkStealingPool

使用得例子为:
在这里插入图片描述
经分析其底层实现方式为:

1、无界线程池 底层实现为ThreadPoolExecutor

public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
其参数得意思为:
如果我们执行任务,一次启动了30个任务,由于其corePoolSize=0,所以30个任务都会被加入BlockingQueue中,然后我们新建新得线程去执行队列中得任务。如果20个任务都执行完毕。从线程闲置时开始倒计时,记时60m后关闭线程。最后线程池中的线程全部被回收并关闭。
注意:cached Thread Pool,老的可用线程将被新的任务触发重新执行。如果线程超过60秒没有执行,那么他将被终止并从池中删除

2、有界线程池 底层实现也为ThreadPoolExecutor

具体源码为:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}

通过参数分析得:
1、corePoolSize 的数量 = nThreads    (maximumPoolSize = corePoolSize  ) 
例子:如果我们一次性执行20个任务,线程池中会启动 nThreads个线程,剩下的任务进入队列BlockingQueue。
参数  keepAliveTime = 0 ,表示某个线程任务执行完毕后,马上检查是否还有其它任务。最后 最后线程池中的线程,即使没有任务,也会保留nThreads (待验证)

3、单线程池 实现方式通过ThreadPoolExecutor

public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
//线程池中最多只有一个线程
超过1的任务,进入队列等待

4、调度线程池 底层实想ScheduledThreadPoolExecutor

public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

5、单线程调度线程池

public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1, threadFactory));
}

6、public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值