Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在使用执行器运行多个线程时立即捕获错误?_Java_Multithreading_Exception_Executorservice - Fatal编程技术网

Java 如何在使用执行器运行多个线程时立即捕获错误?

Java 如何在使用执行器运行多个线程时立即捕获错误?,java,multithreading,exception,executorservice,Java,Multithreading,Exception,Executorservice,代码中的第二个线程将抛出一个除法为0的异常,但我将仅在第一个线程完成后捕获它。第一个线程可以运行几天,因此这意味着只有在异常发生几天后,我才能捕获它。 我能在不子类化ThreadPoolExecutor和重写afterExecute的情况下以某种方式解决这个问题吗 这是我的密码: ExecutorService executor = Executors.newCachedThreadPool(); Future<Integer> future = executor.

代码中的第二个线程将抛出一个除法为0的异常,但我将仅在第一个线程完成后捕获它。第一个线程可以运行几天,因此这意味着只有在异常发生几天后,我才能捕获它。 我能在不子类化ThreadPoolExecutor和重写afterExecute的情况下以某种方式解决这个问题吗

这是我的密码:

    ExecutorService executor = Executors.newCachedThreadPool();

    Future<Integer> future = executor.submit(new MyTestC(4000));
    Future<Integer> future2 = executor.submit(new MyTestC(0));

    ArrayList<Future<Integer>> futures = new ArrayList<>();
    futures.add(future); futures.add(future2);

    for(Future<Integer> f: futures)
    {
        try {
            int result = f.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

class MyTestC implements Callable<Integer> {

int sleep;

public MyTestC(int sleep)
{
    this.sleep = sleep;
}

@Override
public Integer call() throws Exception {
    if(sleep > 0)
        Thread.sleep(sleep);

    //If 0 will throw exception:
    int tmp = 4/sleep;

    return sleep;
}
ExecutorService executor=Executors.newCachedThreadPool();
Future-Future=executor.submit(新的MyTestC(4000));
Future future2=执行者提交(新MyTestC(0));
ArrayList futures=新的ArrayList();
期货。添加(期货);期货.add(future2);
for(未来f:未来)
{
试一试{
int result=f.get();
系统输出打印项次(结果);
}捕获(中断异常|执行异常e){
e、 printStackTrace();
}
}
类MyTestC实现了可调用的{
智力睡眠;
公共MyTestC(int sleep)
{
这个。睡眠=睡眠;
}
@凌驾
公共整数调用()引发异常{
如果(睡眠>0)
睡眠;
//如果0将引发异常:
int tmp=4/睡眠;
恢复睡眠;
}

}

您可以使用解决此问题。它将按照期货完成的顺序返回期货。

Nice,直到关于
ExecutorCompletionService
+1.