2014-09-01 69 views
3

我使用ThreadPoolExecutor管理的线程数,我可以通过ThreadFactory->newThread() 赶上创建线程池一个新的线程的情况下,但现在我知道如何捕捉杀死线程的事件,按照以下配置停留2分钟。检测空闲时的ThreadPoolExecutor线程被杀害

我hae搜索了一个侦听器的方法,但找不到。

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()); 
    } 
+0

我不明白你的问题。 – 2014-09-01 20:55:09

+0

更新了我的问题,我真正想要的是检测线程被执行者杀死的事件的情况。 – 2014-09-01 21:03:30

+0

执行程序不会终止线程。线程在其run()方法返回时停止。 – 2014-09-01 21:04:48

回答

0

在的ThreadPoolExecutor类有一组工人,这是可运行的类跑了通过在池中的线​​程。

当worker完成workerDone回调时执行。在那里你会看到一个tryTerminate方法被调用。这是决定是否终止线程的方法。你应该能够在这一点上

/** 
* Performs bookkeeping for an exiting worker thread. 
* @param w the worker 
*/ 
void workerDone(Worker w) { 
    final ReentrantLock mainLock = this.mainLock; 
    mainLock.lock(); 
    try { 
     completedTaskCount += w.completedTasks; 
     workers.remove(w); 
     if (--poolSize == 0) 
      tryTerminate(); 
    } finally { 
     mainLock.unlock(); 
    } 
} 

/* Termination support. */ 

/** 
* Transitions to TERMINATED state if either (SHUTDOWN and pool 
* and queue empty) or (STOP and pool empty), otherwise unless 
* stopped, ensuring that there is at least one live thread to 
* handle queued tasks. 
* 
* This method is called from the three places in which 
* termination can occur: in workerDone on exit of the last thread 
* after pool has been shut down, or directly within calls to 
* shutdown or shutdownNow, if there are no live threads. 
*/ 
private void tryTerminate() { 
    if (poolSize == 0) { 
     int state = runState; 
     if (state < STOP && !workQueue.isEmpty()) { 
      state = RUNNING; // disable termination check below 
      addThread(null); 
     } 
     if (state == STOP || state == SHUTDOWN) { 
      runState = TERMINATED; 
      termination.signalAll(); 
      terminated(); 
     } 
    } 
} 
+0

这不会触发事件 – 2014-09-01 21:22:20

+0

那么你需要做一堆配置来实现这一点。我会说配置线程池大小为一。同时运行两个作业并确保keepAliveTime较低。然后会有两个线程活着,当工作完成时,其中一个会被杀死。为什么你想知道它在哪里处理? – Bren 2014-09-01 21:33:45

+0

你在看什么实现(及其版本)?我在Oracle JDK 8中没有看到'workerDone'方法。 – 2014-09-01 22:40:56

0

ThreadPoolExecutor不会杀死线程调试。它将从ThreadFactory中检索新线程并让它们为run a Worker。所有这个工作者都是循环的,试图从底层的BlockingQueue中检索Runnable

如果它得到一个,它会调用它上面的run

如果allowCoreThreadTimeOuttrue,你有比核心数量更多的工人,那么keepAliveTime值用于轮询该标的BlockingQueue。如果poll返回null,则工作人员(可能)被删除。发生了一些额外的清理操作,并且各种方法调用从方法return中弹出,直到最终Worker#run()方法终止并且包含的​​线程结束。

没有在那个流程中ThreadPoolExecutor提供任何挂钩通知。

您可以定期查询ThreadPoolExecutor#getPoolSize()ThreadPoolExecutor#getLargestPoolSize()的信息。