我有一个线程,它有一个传入的作业队列(一个包含作业描述的 LinkedList
)。当没有工作可处理时,线程会在队列中用 wait()
阻塞。外部作业调度程序对象在将新作业放入队列时使用 notify()
将其唤醒。
在我的程序关闭时,我在线程上调用了 interrupt()
。当线程等待 wait()
中的作业时,这会引发 InterruptedException
。我的问题是:如果我在 Thread 没有阻塞但在做某种工作时中断它会发生什么,处理的项目是队列中的最后一个(因此队列现在是空的)并且执行通过 isInterrupted()
在设置中断标志之前检查以便再次调用 wait()
?它会抛出 InterruptedException
因为已经设置了中断标志还是线程永远等待因为新作业永远不会到达队列并且没有人可以中断等待?
最佳答案
是的,您的中断线程将在调用 wait() 时抛出 InterruptedException。这很容易自行测试。
public class TestInt {
public static void main(String[] args) throws Exception
{
Thread.currentThread().interrupt();
synchronized(TestInt.class) {
TestInt.class.wait();
}
}
}
另外,请注意 Object.wait()
的 javaodc:
InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
关于java - 线程中断 : will it cancel oncoming wait() call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698977/