2017-01-19 58 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已弃用。相反,你可以打断当前的线程。