gpt4 book ai didi

Java 并发实践 “Listing 7.9. Interrupting a task in a dedicated thread.” 。预定 taskThread.interrupt() 的目的是什么?

转载 作者:行者123 更新时间:2023-12-04 19:25:09 26 4
gpt4 key购买 nike

我正在阅读 Java Concurrency in Practice 并遇到以下代码片段。

public static void timedRun(final Runnable r,
long timeout, TimeUnit unit)
throws InterruptedException {
class RethrowableTask implements Runnable {
private volatile Throwable t;
public void run() {
try { r.run(); }
catch (Throwable t) { this.t = t; }
}
void rethrow() {
if (t != null)
throw launderThrowable(t);
}
}
RethrowableTask task = new RethrowableTask();
final Thread taskThread = new Thread(task);
taskThread.start();
cancelExec.schedule(new Runnable() {
public void run() { taskThread.interrupt(); }
}, timeout, unit);
taskThread.join(unit.toMillis(timeout));
task.rethrow();
}
timedRun方法用于运行任务 r一个时间范围内。此功能可以通过 taskThread.join(unit.toMillis(timeout)); 实现.所以, 为什么我们需要预定 taskThread.interrupt(); ?

最佳答案

This feature can be implemented by taskThread.join(unit.toMillis(timeout));



这不是真的。加入时限刚刚 determines when the joining thread will give up waiting .它不会影响被超时限制的线程。预定 interrupt告诉正在运行的线程在超时到期后自行关闭。如果它不存在,该线程将继续消耗资源。据推测,该方法的重点是防止这种情况发生。

关于Java 并发实践 “Listing 7.9. Interrupting a task in a dedicated thread.” 。预定 taskThread.interrupt() 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59558077/

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