异步编程学习之路(五)-线程池原理及使用,好文推荐

本文详细介绍了Java线程池的工作原理,包括如何判断线程是否需要退出,线程池的配置参数如最大线程数、核心线程数、存活时间及其单位、任务队列的选择等。同时,分析了四种任务拒绝策略,并提醒开发者避免直接使用Executors创建线程池,而应自定义阻塞队列大小以避免潜在风险。文章通过实例展示了如何使用固定大小线程池(FixedThreadPool)并给出了核心架构的学习资料。
摘要由CSDN通过智能技术生成
  • current configuration settings, or returns null if this worker

  • must exit because of any of:

    1. There are more than maximumPoolSize workers (due to
  • a call to setMaximumPoolSize).

    1. The pool is stopped.
    1. The pool is shutdown and the queue is empty.
    1. This worker timed out waiting for a task, and timed-out
  • workers are subject to termination (that is,

  • {@code allowCoreThreadTimeOut || workerCount > corePoolSize})

  • both before and after the timed wait, and if the queue is

  • non-empty, this worker is not the last thread in the pool.

  • @return task, or null if the worker must exit, in which case

  •     workerCount is decremented
    

*/

private Runnable getTask() {

boolean timedOut = false; // Did the last poll() time out?

for (;😉 {

int c = ctl.get();

int rs = runStateOf©;

// Check if queue empty only if necessary.

if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {

decrementWorkerCount();

return null;

}

int wc = workerCountOf©;

// Are workers subject to culling?

boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

if ((wc > maximumPoolSize || (timed && timedOut))

&& (wc > 1 || workQueue.isEmpty())) {

if (compareAndDecrementWorkerCount©)

return null;

continue;

}

try {

Runnable r = timed ?

workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :

workQueue.take();

if (r != null)

return r;

timedOut = true;

} catch (InterruptedException retry) {

timedOut = false;

}

}

}

根据当前配置设置执行阻塞或定时等待任务,如果工作线程存在以下原因的话则退出并返回null:

1、工作线程超过线程池最大线程数(因为设置了线程池的最大线程数)。

2、线程池已停止。

3、关闭线程池&&队列为空。

4、该线程在等待任务的时候超时,超时的线程将被终止。(allowCoreThreadTimeOut || workerCount > corePoolSize)

还有一点需要注意的是下面这句代码:

boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) {

if (compareAndDecrementWorkerCount©)

return null;

continue;

}

也就是说在((当前工作线程数 > 最大线程数) || (当前队列不为空 && (允许核心线程超时 || 当前工作线程数 > 核心线程)) && (当前工作线程数 > 1 || 队列为空) 的时候GC会将线程回收。

5、unit(存活时间单位)

参数keepAliveTime的时间单位,有7种取值,在TimeUnit类中有7种静态属性:

TimeUnit.DAYS; //天

TimeUnit.HOURS; //小时

TimeUnit.MINUTES; //分钟

TimeUnit.SECONDS; //秒

TimeUnit.MILLISECONDS; //毫秒

TimeUnit.MICROSECONDS; //微妙

TimeUnit.NANOSEC

  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值