异步编程学习之路(五)-线程池原理及使用,java架构师面试问题

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.NANOSECONDS; //纳秒

6、workQueue(任务阻塞队列)

workQueue是用来存储等待执行的任务,一般有三种选择(ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue),他们的初始化参数如下:

/**

  • Creates an {@code ArrayBlockingQueue} with the given (fixed)

  • capacity and default access policy.

  • @param capacity the capacity of this queue

  • @throws IllegalArgumentException if {@code capacity < 1}

*/

public ArrayBlockingQueue(int capacity) {

this(capacity, false);

}

/**

  • Creates an {@code ArrayBlockingQueue} with the given (fixed)

  • capacity and the specified access policy.

  • @param capacity the capacity of this queue

  • @param fair if {@code true} then queue accesses for threads blocked

  •    on insertion or removal, are processed in FIFO order;
    
  •    if {@code false} the access
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值