我正在调用使用invokeAll()的线程列表。 AFAIK invokeAll()仅在所有线程完成其任务时才会返回。如果线程列表中的任何线程发生异常,则中断所有线程
ExecutorService threadExecutor = Executors.newFixedThreadPool(getThreadSize());
List<Future<Object>> future = w_threadExecutor.invokeAll(threadList);
当所有线程完成
for (Future<Object> w_inProgressThread : w_future)
{
//
它停止在其出现异常,而不是剩下的一个线程这就是所谓的。 如果任何线程抛出异常,是否有办法停止所有其他线程? 或者我必须提交每个任务而不是invokeAll()?我试过在invokeAll()上使用invokeAny()而不是cancell剩余的任务 invokeAny():如果其中一个任务完成(或引发异常),则其余的Callable被取消。 编号:http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
更新:
CompletionService<Object> completionService = new ExecutorCompletionService<Object>(w_threadExecutor);
List<Future<Object>> futures = new ArrayList<Future<Object>>();
for(Thread w_mt : threadList)
{
futures.add(completionService.submit(w_mt));
}
for (int numTaken = 0; numTaken < futures.size(); numTaken++) {
Future f = completionService.take();
try {
Object result = f.get();
System.out.println(result); // do something with the normal result
} catch (Exception e) {
System.out.println("Catched ExecutionException, shutdown now!");
//threadExecutor.shutdownNow();
Thread.currentThread().interrupt();
for (Future<Object> inProgressThread : futures)
{
inProgressThread.cancel(true);
}
break;
}
更新1:
至于建议由waltersu我试图
ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
CompletionService<Object> completionService = new ExecutorCompletionService<Object>(threadExecutor);
List<Future<Object>> futures = new ArrayList<Future<Object>>();
futures.add(completionService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
String s=null;
// Thread.sleep(1000);
for(int i=0; i < 1000000; i++){
int j =10 ;
if(i==100)
{
s.toString();
}
System.out.println("dazfczdsa :: " + i);
}
//throw new Exception("This is an expected Exception");
return s;
}
}));
futures.add(completionService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
for(int i=0; i < 1000000; i++){
int j =0 ;
j= j+2;
System.out.println("dasa :: " + i);
}
Thread.sleep(3000);
return "My First Result";
}
}));
while (futures.size() > 0) {
Future f = completionService.take();
futures.remove(f);
try {
Object result = f.get();
System.out.println(result); // do something with the normal result
} catch (ExecutionException e) {
System.out.println("Caught exception from one task: " + e.getCause().getMessage() + ". shutdown now!");
f.cancel(true);
threadExecutor.shutdownNow();
break;
}
}
System.out.println("Main exists");
这个时候发生异常
threadExecutor.notifyAll()中断所有线程 –
@AkashLodha ''从'Object'中的notifyAll()'唤醒在这个对象的监视器上等待的所有线程“。线程不在任何特定对象的显示器上等待,是吗?我错过了什么? – davmac
我假设threadList是想要在同一个对象上锁定的线程。 –