线程池淘汰策略-线程正常执行

在线程池中,核心线程相当于长期员工,需要一直存在,而线程数大于核心线程数时,必然会出现临时工,在空闲时被清除以防浪费线程资源,剩下的线程即作为新的核心线程继续工作

线程池相关代码如下:

 private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?
 
        for (;;) {
            int c = ctl.get();
 
            // Check if queue empty only if necessary.
            if (runStateAtLeast(c, SHUTDOWN)
                && (runStateAtLeast(c, STOP) || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }
 
            int wc = workerCountOf(c);
 
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
 
            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    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;
            }
        }
    }

关键变量及方法分析:
timedOut:线程空闲时间是否已经超时

allowCoreThreadTimeOut:是否允许核心线程超时被回收,一般而言核心线程是允许超时等待新任务执行的,默认视为false;需要回收核心线程时自定义为true,此时timed也会一直为true

timed:是否有worker(即线程池中的线程)需要被“裁员”,当线程数量超过核心线程数时为ture,

否则取决于allowCoreThreadTimeOut

compareAndDecrementWorkerCount():通过CAS竞争“下岗”资格,使线程数量-1

c:线程池状态

wc:线程的数量

流程1:
boolean timedOut = false; // Did the last poll() time out?
 
        for (;;) {
            int c = ctl.get();
 
            // Check if queue empty only if necessary.
            if (runStateAtLeast(c, SHUTDOWN)
                && (runStateAtLeast(c, STOP) || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }
 
            int wc = workerCountOf(c);
当getTask()方法被调用时,每个线程都会进入一个死循环,并在进入循环前将timedOut设置为false(因为此时线程默认都是没有超时的)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值