2013-10-30 73 views
-1

有沒有辦法告訴ExecutorService在固定線程池方案中關閉空閒線程?關閉空閒線程ExecutorService

問候!

::編輯: 好吧,我感到沮喪。我現在已經切換到ThreadPoolExecutor的,讓我來指定KeepAliveTime的,使用下面的構造:

private final LinkedBlockingQueue<Runnable> threadPool = new LinkedBlockingQueue<Runnable>() 
public Crawler(String startingUrl, int numThreads, int depth) { 

    System.setProperty("http.agent", ""); 
    // System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "info"); 
    this.url = startingUrl; 
    this.maxDepth = depth; 

    executorService = new ThreadPoolExecutor(
      numThreads, 
      numThreads, 
      2000, 
      TimeUnit.MILLISECONDS, 
      threadPool, 
      new ThreadPoolExecutor.CallerRunsPolicy()); 


    databaseHandler = new DatabaseHandler(); 
    try { 
     databaseHandler.init(); 
    } catch (final SQLException e) { 
     e.printStackTrace(); 
    } 
} 

// this method is invoked by each Runnable when it found new links 
@Override 
public void queueLink(String link, int currentDepth) throws Exception { 
    if (currentDepth < maxDepth) { 
     final LinkFinder lf = new LinkFinder(link, currentDepth, this); 
     executorService.execute(lf); 

    } else { 
     System.out.println("max depth reached!"); 
     System.out.println("num queued tasks: " + threadPool.size()); 
    } 
} 

每個新的Runnable接收電流深度屬性。在每個Runnable currentDepth的最後一行上加1。當然,「達到最大深度」按預期打印輸出,以及「num queued tasks:0」。然而線程繼續運行數小時。

我的印象是keepAliveTime和TimeUnit.MILLISECONDS會確保在閒置兩秒後關閉線程(因爲沒有其他任務排隊)。

我錯過了什麼?我的意思是,我可以計算我點擊else語句的次數,然後手動關閉執行程序,但由於ThreadPoolExecutor已經提供了基於時間的行爲,我寧願堅持這一點。

現在我認爲它與我設定的政策有關......要研究這一點。謝謝反正

關心!

+0

setKeepAliveTime動態的減少線程池的大小()? – kosa

+0

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html 向我展示該方法;) –

+0

您需要轉到javadoc以供實施。 – kosa

回答

0

setKeepAliveTime(long time, TimeUnit unit)

您可以通過setCorePoolSize(int corePoolSize)