2014-02-27 150 views
3

這是一個非常簡單的代碼:FutureTask保持活躍

FutureTask<Integer> task = new FutureTask<>(new 
      Callable<Integer>(){ 
       @Override 
       public Integer call() throws Exception { 
        int i =0; 
        while(i<10){ 
         i++; 
        } 

        return 0; 
       } 

    }); 

計數10,然後退出......容易。

我執行這樣的:

Executor executor = Executors.newCachedThreadPool(); 
    executor.execute(task); 
    try { 
     task.get(3000, TimeUnit.MILLISECONDS); 
     System.out.println("Everything was ok"); 
    } catch (InterruptedException | ExecutionException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (TimeoutException ex){ 
     boolean result = task.cancel(true); 
     System.out.println("the task has timed out "+result); 
    } 

我得到「一切正常」到控制檯,因此任務正確執行並返回。 但是線程仍然存在!我可以通過在eclipse中執行它來看到它:標記正在執行的程序的紅色方塊仍處於活動狀態。 但我的主要關閉後打印「一切正常」,所以它一定是那個任務。 爲什麼它不關閉?我怎樣才能關閉它?

我看到一些ExecutorService類的例子,它有一個關閉方法,但我不想關閉整個線程池,因爲我仍然需要它活動接受其他任務,我只想要關閉任務!

回答

3

Executors.newCachedThreadPool()的文檔聲明它「創建一個線程池,用於根據需要創建新線程,但將在以前構建的線程可用時重用它們......未使用六十秒的線程被終止並從緩存「。

你等了六十秒嗎?