gpt4 book ai didi

java - 执行者与线程

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:42 24 4
gpt4 key购买 nike

我正在尝试运行以下代码:

public static void main(String[] args){
ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2);

Runnable r = new Runnable() {
@Override
public void run() {
throw new RuntimeException();
}
};
service.execute(r );
ScheduledFuture<?> schedule = service.schedule(r, 0, TimeUnit.SECONDS);
new Thread(r).run();
}

关于上述问题,我有以下问题:

  1. 有什么方法可以捕获和响应执行程序线程上发生的异常吗?
  2. 为什么创建的线程的异常显式传播到主线程,但使用执行程序服务的两次执行都没有传播该错误?怎么会发现这个错误?

编辑:想到另一个问题:

  1. 如何停止我安排的给定周期性任务,比方说在 N 次重复或 N 分钟后?

最佳答案

问题 2 非常简单 - 您实际上并没有启动新线程,您只是调用 run(),它在原始线程中同步运行。您应该调用 start(),此时异常不会传播回来。

至于在 ScheduledExecutorService 中处理异常 - 如果您调用 Future.get() , 它会抛出 ExecutionException如果原始任务抛出异常,将原始异常暴露为原因:

Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.

如果您需要响应异常而不阻止 future 的完成,您可以将“真实的”Runnable 包装在另一个刚刚委托(delegate)给原始 run() 方法,但带有适当的 try/catch block 。

关于java - 执行者与线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12809185/

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