我正在調用使用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是想要在同一個對象上鎖定的線程。 –