2017-01-19 54 views
0

我有一個應用程序,其中有多個線程。我希望它們按順序執行,所以我選擇executorService進行多線程。如果任何一個線程(運行方法)出錯,我想移動到網絡線程,以便最後我可以知道有多少線程成功完成(需要計數)。我的示例代碼:執行器服務中斷處理

主類:

 public class MySampleClass{ 
     ExecutorService executor = Executors.newSingleThreadExecutor(); 
      for(int i=0; i<=100;i++){  
      executor.submit(new ThreadClass()); 
      } 
//After all threads executed now to shutdown executor 
executor.shutdown() 
executor.awaitForTermination(1,Time.MILLISECONDS); 

我的樣本Thread類:

public class ThreadClass implements Runnable{ 
     @override 
     public void run(){ 
      boolean isCompleted= doAction(); 
      if(!isCompleted){ 
        // I want here to stop this thread only..what to do ? 
        //executor.shutdown will stop all other threads 
       } 
     } 
} 

任何建議,該怎麼辦?我做錯了嗎?

+0

你爲什麼不''回來;'? –

+0

那些不是線程,那些是_tasks_。任務是一項需要完成的工作。你的'SingleThreadExecutor'是一個使用線程來執行你的任務的對象。 –

回答

0
Thread.currentThread().interrupt(); 

你不應該停止一個線程。有一個reason Thread.stop已棄用。相反,你可以打斷當前的線程。