线程池的扩展

ThreadPoolExecutor是一个可以扩展的线程池,其提供了beforeExecute(), afterExecute()与terminated()三个接口对线程池进行控制。

    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        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); //钩子1
                    try {
                        task.run();
                        afterExecute(task, null); //钩子2-NORMAL
                    } catch (Throwable ex) {
                        afterExecute(task, ex);  //钩子2-THROWABLE
                        throw ex;
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

在ThreadPoolExecutor中,beforeExecute()与 afterExecute()默认为空。在实际场景中,通过继承ThreadPoolExecutor,或是在声明时进行重载,可以对其进行扩展一实现对线程池运行状态的跟踪。这两个钩子函数的提供有助于应用程序的调试与诊断。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容