【发布时间】:2016-10-19 03:45:05
【问题描述】:
我正在使用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() 但没有取消剩余任务 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
notifyAll()fromObject"唤醒所有在这个对象的监视器上等待的线程"。线程没有在任何特定对象的监视器上等待,是吗?我错过了什么? -
我假设 threadList 是想要锁定同一对象的线程。
-
如果您打算在一个线程出错时关闭所有工作,您可以
future.cancel(true)任务 - 如果任务正在运行,这将中断线程。 -
如果发生异常,我无法在父线程中获得控制权。它只有在完成所有线程之后才会出现。
标签: java multithreading threadpool executorservice java.util.concurrent