我有一个应用程序,其中有多个线程。我想让它们在order.so中执行,我选择executorService作为多线程。如果任何一个线程(run方法)出错,我想转到net线程,这样到最后我就可以知道有多少线程成功完成(需要计数).My示例代码:
主类:
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
}
}
}有什么建议吗?我是不是做错了?
发布于 2017-01-20 01:36:09
Thread.currentThread().interrupt();你不应该停止一个线程。有一个reason Thread.stop已弃用。相反,您可以中断当前线程。
发布于 2017-01-20 01:28:26
您可以使用Callable而不是Runnable。如果这样做,submit方法将返回一个Future (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html)实例,您可以在该实例上验证可调用对象是否以正确的方式工作。文档对此进行了说明:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)
希望我的解释是正确的。
https://stackoverflow.com/questions/41747648
复制相似问题