我尝试用这个可怕的代码使标准 ExecutorService
的固定线程池的线程崩溃,以测试它对传递给 ExecutorService 的任务中发生的异常和错误的弹性
:
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
throw new RuntimeException("Trying to kill the thread");
});
Thread.sleep(100);
executorService.execute(() -> {
System.out.println("still executing");
});
但是第二个任务打印出 still executing
所以我认为异常被捕获或者 Thread
实例无论如何都重新启动了。
怎么了?我可以相信无论任务内部发生什么(小于 System.exit()
)其他提交的任务都将继续由池执行吗?
最佳答案
您的执行程序服务使用线程池。如果一个线程被杀死,另一个线程将被实例化以执行下一个任务。
您调用 Executors.newFixedThreadPool(1);
仅对 Activity 线程数设置限制。
为了停止执行器服务,你必须调用:
executorService.shutdown();
关于java - 有没有办法无意中停止 Executor 的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794306/