0

我已阅读http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

我决定通过以下方式使我的锁定不可取消任务

try {
    lockedRecords.wait();
} catch (InterruptedException e) {
    interrupted = true;
}

但是有没有必要

} finally {
    if (interrupted) {
        Thread.currentThread().interrupt();
    }
}

文章说你应该调用 interrupt() 来保持中断状态。我还是很模糊,那如果我设置.interrupt呢?接下来发生什么?对此有点迷失......任何输入?

它给我的程序带来什么价值?请用外行术语解释,非常感谢:D

4

2 回答 2

2

这里重要的是示例中未编写的代码。示例 ( getNextTask) 中的方法可用于:

while (!Thread.interrupted()) {
   Task task = getNextTask(queue);  
   doSomething(task);
}
System.out.println("The thread was interrupted while processing tasks.");
System.out.println("...stopped processing.");

上面的while循环将永远执行,除非有人中断了运行此循环的线程。

但是,如果没有像 in 那样重置中断状态getNextTask,当有人试图在线程 in 时中断线程时queue.takegetNextTask中断就会丢失,我上面写的代码将永远不会停止循环。

IBM 网页上示例的全部要点是,在吞下中断时必须非常小心,因为它可能会意外地使线程无法中断。

于 2011-08-09T23:45:00.600 回答
0

只要InterruptedException您知道当前线程将在您的任务完成并返回后终止就可以了。

Problems may arise when using some thread pool, like ExecutorService, where usually the threads continue to run after a task has completed, waiting for the next task to come. In this case the pooled thread should be notified it was interrupted so that it can do whatever is appropriate in this situation, e.g. perform a clean shutdown and exit.

Thus, it is good practice and more safe to make sure you restore the interrupted state before returning from your routine.

于 2011-10-27T14:18:19.373 回答