执行人服务中断处理

时间:2017-01-19 17:06:18

标签: java multithreading

我有一个应用程序,其中有多个线程。我希望它们按顺序执行。所以我选择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);

我的示例线程类:

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  
               }
       }
}

任何建议怎么办?我做错了吗?

2 个答案:

答案 0 :(得分:0)

您可以使用Callable而不是Runnable。如果这样做,submit方法将返回一个Future(http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html)实例,您可以在该实例上验证callable是否以正确的方式工作。文档解释了它:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)

希望我以正确的方式解释。

答案 1 :(得分:0)

Thread.currentThread().interrupt();

你不应该停止一个线程。有一个reason Thread.stop已弃用。相反,你可以打断当前的线程。

相关问题