【问题标题】:How to catch errors instantly when running multiple threads with executors?使用执行程序运行多个线程时如何立即捕获错误?
【发布时间】:2013-03-28 21:17:16
【问题描述】:

我的代码中的第二个线程会抛出一个除以 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;
}

}

【问题讨论】:

    标签: java multithreading exception executorservice


    【解决方案1】:

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

    【讨论】:

    • 很好,关于ExecutorCompletionService。 +1。
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多