2016-12-15 22 views
2

代碼:的ExecutorService殺得螺紋

//List all threads: 
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet(); 
System.out.println(runningThreads.toString()); 

//Thread creation: 
ExecutorService executorService = Executors.newSingleThreadExecutor(); 
executorService.execute(this); 

//Thread termination: 
executorService.shutdownNow(); 

//List all threads: 
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet(); 
System.out.println(runningThreads.toString()); 

我期望被打印出來是完全一樣的兩個時間,但什麼我得到是打印出來的線程所創建的列表包括在結果中

我該如何徹底銷燬一個線程,以至於無處可尋?

+0

您應該等待關閉過程完成。線程可能尚未終止。 – glee8e

回答

1

shutdownNow()嘗試停止正在運行的線程,但它的API文檔說:

這種方法不會等待正在執行的任務終止。使用awaitTermination來做到這一點。

因此,當調用shutdownNow()後的代碼返回時,線程仍可能正在運行。還要注意你需要確保線程中運行的任務實際上終止; shutdownNow()不會殺死線程,它只會嘗試中斷它。

正如文檔所述,在調用shutdownNow()之後,請等待線程停止後再調用executorService.awaitTermination(...)

+0

如果它永遠不會終止?看起來,即使我把'awaitTermination'放了幾天,它就會掛起,永遠不會殺死線程 – Hooli

+1

@Hooli:你永遠不會顯示你要提交給執行者的任務。如果它不響應中斷而退出(消耗InterruptedException並持續循環或在I/O上阻塞),則它不會終止。 –

+0

@NathanHughes:把我的線程從while(true){...}改爲while(!this.isInterrupted()){...}'是個好主意嗎? – Hooli