gpt4 book ai didi

java - 为什么我们不应该在借用的线程上安排中断?

转载 作者:行者123 更新时间:2023-11-30 03:12:47 25 4
gpt4 key购买 nike

以下是《Java Concurrency in Practice》一书的摘录:

//Scheduling an interrupt on a borrowed thread. Don’t do this.

private static final ScheduledExecutorService cancelExec = ...;

public static void timedRun(Runnable r,long timeout, TimeUnit unit) {
final Thread taskThread = Thread.currentThread();
cancelExec.schedule(new Runnable() {
public void run() { taskThread.interrupt(); }
}, timeout, unit);
r.run();
}

作者说:

This is an appealingly simple approach, but it violates the rules: you should know a thread’s interruption policy before interrupting it. Since timedRun can be called from an arbitrary thread, it cannot know the calling thread’s interruption policy. If the task completes before the timeout, the cancellation task that interrupts the thread in which timedRun was called could go off after timedRun has returned to its caller. We don’t know what code will be running when that happens, but the result won’t be good. (It is possible but surprisingly tricky to eliminate this risk by using the ScheduledFuture returned by schedule to cancel the cancellation task.)

Further, if the task is not responsive to interruption, timedRun will not return until the task finishes, which may be long after the desired timeout (or even not at all). A timed run service that doesn’t return after the specified time is likely to be irritating to its callers.

我的问题:

  1. 超时是什么意思?
  2. 什么是取消任务

最佳答案

超时意味着taskThread在任务被中断之前有一个分配的时间间隔来运行任务。取消任务是执行中断的专用任务(在单独的线程上)。

这里的危险是:

  • 代码正在中断线程而不是取消任务。被中断的线程可能是线程池的一部分,并且可能已经完成了任务并且正在执行一些完全不同的任务。

  • 被中断的任务可能无法正确使用中断作为完成其工​​作的指示器,或者是否可能执行诸如阻塞 I/O 之类的操作,而无法检查中断状态,因此无法保证总的来说,超时是有效的。

关于java - 为什么我们不应该在借用的线程上安排中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272581/

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