gpt4 book ai didi

java - 'Thread termination due to failure'指的是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:49 25 4
gpt4 key购买 nike

ExecutorService 的 javadoc 有时会提到线程“由于失败”而终止的情况。但是,目前尚不清楚这指的是哪种故障。

例如,single thread executor文档说

if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks

我本来以为这种情况可能发生在Exception的情况下,也可能是RuntimeException,但似乎并不是这样。运行以下代码似乎给出了相同的线程名称和线程 ID。

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
System.out.println("Hello from " + Thread.currentThread().getName()+ " " + Thread.currentThread().getId());
throw new NullPointerException("Test");
});

executor.submit(() -> {
System.out.println("Hello 2 from " + Thread.currentThread().getName() + " " + Thread.currentThread().getId());
});

这段代码的输出是:

Hello from pool-1-thread-1 12
Hello 2 from pool-1-thread-1 12

即使在 NullPointerException 的情况下,似乎也在重复使用同一个线程。

那么 Javadoc 指的是哪种“失败”?

最佳答案

这是一个有趣的问题。按照 ThreadPoolExecutor 中的代码,当 Runnable 传递给 execute() 方法时,线程将被丢弃。

当您调用 submit() 时,执行程序会为 FutureTask 类型的可调用/可运行对象创建一个包装器。 FutureTask.run() 有一些逻辑来捕获异常并存储它们(因此,您可以从 Future 中查询它)。在这种情况下,异常永远不会到达 ThreadPool,因此不会丢弃线程。

关于java - 'Thread termination due to failure'指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725098/

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