Java线程池之:如何回收临时线程

首先确定Java线程池回收临时线程的基本思想,当一个线程在指定时间内无法从阻塞队列获取任务时,判断当前线程数是否超过最大线程数,超过则回收该线程。

具体代码实现部分如下:

首先是runWroker()部分,worker是线程池中事实上的线程,runWorker()方法是worker工作的核心方法,该方法会循环尝试从阻塞队列获取任务并执行,getTask()方法尝试从阻塞队列中获取任务,当满足回收条件(超时 && 超过核心线程数),会退出循环,执行线程回收工作.

final void runWorker(ThreadPoolExecutor.Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask; // 获取worker中的任务
    w.firstTask = null; // 将worker中的任务置为空
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        // 循环尝试从队列中获取任务并执行
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            if ((runStateAtLeast(ctl.get(), STOP) ||
                    (Thread.interrupted() &&
                            runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                wt.interrupt();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    task.run(); // 执行任务
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        // 从循环中退出,意味着该线程要被回收,处理回收过程
        processWorkerExit(w, completedAbruptly);
    }
}

getTask()方法如下, 其循环从阻塞队列中获取任务, 如果成功获取就返回; 否则, poll()方法会在超过限定时间后返回null, 触发判断机制, 此时如果工作线程数大于核心线程数, 就会返回null, 在runWroker()方法中回收工作线程.

private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?
    // 循环尝试获取任务
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
            decrementWorkerCount();
            return null;
        }

        int wc = workerCountOf(c);

        // Are workers subject to culling?
        // timed 包含超过核心线程数
        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) : // 关键,poll()方法可以设置超时参数,超时会返回null
                    workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值