中断允许在线程上下文中停止一些长/阻塞任务。仅当有人为给定线程设置了“被中断”标志时,才会发生 InterruptedException。
现在关于等待()。当你的线程 A 在 Condition.await() 上等待时,通常这意味着它被
LockSupport.park(对象拦截器);(-> sun.misc.Unsafe.park(boolean bln, long l) 用于热点)。像这样的东西:
public void await() throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
while (still_waiting) {
LockSupport.park(this);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
}
现在让我们假设用户停止了应用程序。主线程调用 A.interrupt() 来完成您的线程 A.interrupt() 在本机 Thread.interrupt0() 中实现。此调用设置线程的“被中断”标志并解除线程 A 的驻留,线程看到它被中断并抛出 InterruptedException。
如何捕获 InterruptedException 取决于系统要求。如果你的线程在循环中做了一些工作,你应该打破循环让线程完成。此外,如果您刚刚捕获了 InterruptedException,最好为当前线程设置“被中断”标志:
try {
...
some.await();
}
catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
一篇旧但仍然很好的文章:http ://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-