我是 Java concurrecny 的新手,目前正在阅读此内容: Java Tutorial-Interrupts但我真的不明白在哪里以及为什么应该使用中断。有人可以给我一个例子(代码)以便我更好地理解它吗?谢谢
最佳答案
当你想要(咳嗽)中断线程时使用中断——通常意味着停止它的操作。由于各种问题,Thread.stop()
已被弃用,因此 Thread.interrupt()
是告诉线程应该停止运行的方式——它应该进行清理它正在做什么并退出。实际上,程序员可以按照他们想要的任何方式在线程上使用中断信号。
一些例子:
- 您的线程可能会 hibernate 一分钟,然后抓取网页。您希望它停止这种行为。
- 也许您有一个线程正在消耗作业队列,并且您想告诉它没有更多作业正在处理。
- 也许您有许多后台线程需要中断,因为进程正在关闭,而您希望彻底关闭。
当然有很多方法可以完成上述信号发送,但可以使用中断。
Thread.interrupt()
影响正在运行的线程的更强大方法之一是从几个不同的方法抛出 InterruptedException
,其中包括 Thread.sleep( )
、Object.wait()
等。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// i've been interrupted
// catching InterruptedException clears the interrupt status on the thread
// so a good pattern is to re-interrupt the thread
Thread.currentThread().interrupt();
// but maybe we want to just kill the thread
return;
}
此外,我们通常在线程中循环执行某些任务,因此我们检查中断状态:
while (!Thread.currentThread().isInterrupted()) {
// keep doing our task until we are interrupted
}
关于java - java中中断的具体用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12377807/