Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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_Threadpool_Java.util.concurrent - Fatal编程技术网

Java 发生异常时停止线程池中的所有线程

Java 发生异常时停止线程池中的所有线程,java,multithreading,threadpool,java.util.concurrent,Java,Multithreading,Threadpool,Java.util.concurrent,我需要停止执行线程池中的线程,以防其中任何线程引发异常。 我的解决方案是在每个Runnable上引用ExecutorService,并在其上调用shutdownNow()。不确定这是否合适。实际代码更复杂,因为它将电子邮件发送作为一项任务,但为了便于说明,我简化了代码: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.at

我需要停止执行
线程池中的线程,以防其中任何线程引发异常。
我的解决方案是在每个
Runnable
上引用
ExecutorService
,并在其上调用
shutdownNow()
。不确定这是否合适。实际代码更复杂,因为它将电子邮件发送作为一项任务,但为了便于说明,我简化了代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Concurrency {
    private static AtomicInteger counter = new AtomicInteger();

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 20; i++) {
            exec.execute(new Tasku(exec));
        }
    }

    public static class Tasku implements Runnable {
        ExecutorService executorService;

        public Tasku(ExecutorService executorService) {
            this.executorService = executorService;
        }

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(counter.incrementAndGet());
                if (counter.intValue() == 10) {
                    try {
                        throw new ArrayIndexOutOfBoundsException();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        executorService.shutdownNow();
                    }
                }
            }
        }
    }
}
这是处理这种情况的好方法吗?如果没有,怎么做


谢谢

这是一个合理的解决方案。您可以通过覆盖Executor.exec(Runnable r)并提交新的Tasku(r)而不是r来改进它。这样,Executor的界面保持不变。

这是一个合理的解决方案。您可以通过覆盖Executor.exec(Runnable r)并提交新的Tasku(r)而不是r来改进它。这样,Executor的接口保持不变。

为什么要抛出然后捕获相同的异常。为什么不直接调用
shutdownNow()
?模拟一个异常,它只能在本例中是shutdownNow(),但在实际代码中,它是预期的异常。为什么要抛出并捕获相同的异常。为什么不直接调用
shutdownNow()
?模拟一个异常,只有在这个例子中它可以是shutdownNow(),但在真实的代码中会出现异常。谢谢,但我不明白你的改进建议,你能用代码详细说明吗?谢谢,但我不明白你的改进建议,你能用代码详细说明吗?
1
4
6
7
5
9
3
2
10
8