gpt4 book ai didi

java - 我需要处理 executorservice 中的异常吗

转载 作者:行者123 更新时间:2023-11-30 06:01:27 25 4
gpt4 key购买 nike

我需要在 executorservice 中处理运行时异常吗?我在 Spring Boot Web 应用程序中尝试了一个示例,尽管出现异常,代码仍然会执行

这是代码:

@RestController
class WelcomeController {
ExecutorService es = Executors.newSingleThreadExecutor();

@GetMapping("/sayhi")
public String sayHi() {
es.submit(() -> {
System.out.println("hello");

int a = 0;
if (10 / a == 1) {

}
});

return "hi";
}
}

最佳答案

当一个线程中抛出异常时,它不会传播到其他线程,除非您执行某些操作(例如使用 Future)。这里线程引发异常并终止,但程序的其余部分不受影响。

执行器创建一个替换丢失的线程,请参阅 API 文档:

Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed. Unlike the otherwise equivalent newFixedThreadPool(1, threadFactory) the returned executor is guaranteed not to be reconfigurable to use additional threads.

在我看来,让任务处理它们引起的异常是一个好主意。否则,线程就会死亡,池必须启动一个新线程来替换它。这基本上就是评论中链接的文章所说的内容。

关于java - 我需要处理 executorservice 中的异常吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com