我正在使用 ThreadPoolExecutor
来管理线程数,我可以通过 ThreadFactory->newThread()
捕获为 ThreadPool 创建新线程的事件
但是我现在知道如何按照以下配置捕获杀死 2 分钟空闲线程的事件。
我已经搜索了一个监听器方法,但找不到。
public abstract class ThreadPoolEventProcessor<E> implements ThreadFactory{
private BlockingQueue<Runnable> taskQueue;
private ThreadPoolExecutor executor;
protected ThreadPoolEventProcessor(int coreThreadSize, int maxQueueSize) {
taskQueue = new LinkedBlockingQueue<Runnable>(maxQueueSize);
executor = new ThreadPoolExecutor(coreThreadSize, coreThreadSize * 5, 2L, TimeUnit.MINUTES, taskQueue,this);
executor.prestartAllCoreThreads();
}
public Thread newThread(Runnable r) {
return new Thread(r, getWorkerName());
}
最佳答案
ThreadPoolExecutor
不会终止线程。它将从 ThreadFactory
中检索新线程,并让它们运行
Worker
。这个 worker 所做的就是循环,尝试从底层 BlockingQueue
中检索 Runnable
。
如果它得到一个,它会对其调用 run
。
如果 allowCoreThreadTimeOut
为 true
并且您的 worker 数量多于核心数量,则 keepAliveTime
值用于轮询底层 阻塞队列
。如果 poll
返回 null
,则工作人员(可能)被移除。一些额外的清理发生,各种方法调用从堆栈中弹出作为方法 return
,直到最终 Worker#run()
方法终止并且包含线程完成。
在该流程中,ThreadPoolExecutor
没有提供任何通知 Hook 。
您可以定期轮询 ThreadPoolExecutor#getPoolSize()
和 ThreadPoolExecutor#getLargestPoolSize()
以获取信息。
关于java - 检测空闲 ThreadPoolExecutor 线程何时被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612782/