每个线程都有一个boolean属性,表示中断状态,初始值为false。html
正常状况下,只是将线程的中断状态变为true
。线程中能够经过轮询中断状态,作出相应的处理。
若是线程在阻塞状态下,线程将退出阻塞且中断状态将被清除
(即为false),且会抛出InterruptException。
(IO操做忽略)多线程
(1)isInterrupted(),返回当前的中断状态,不会改变中断状态。
(2)static interrupted(),返回当前中断状态,且会清除中断状态。(即第二次调用将返回 false)线程
(1)继续抛出。
若是抛出InterruptedException意味着是一个阻塞方法,那么调用一个阻塞方法则意味着调用者也是一个阻塞方法,应该有某种策略来处理InterruptedException。
(2)捕获InterruptedException,执行清理
,再从新抛出InterruptedException。
(3)再次调用interrupt()。
当由Runnable定义的任务调用一个可中断的方法时,在这种状况下,不能从新抛出InterruptedException,由于Runnable接口的run方法不容许抛出异常。
当一个阻塞方法检测到中断并抛出InterruptedException可是不能从新抛出它,那么应该保留中断发生的证据,以便调用栈中更高层的代码能知道中断,并对中断作出响应
,该任务能够经过调用interrupt()以从新中断当前线程来完成。code
public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } }
如一个IO类会阻塞线程,但不支持中断。则能够写一个新IO类,继承Thread类,重写interrupt方法,在interrupt中关闭IO,最后调用super.interrupt();htm
在进入阻塞前被中断,被称为待决中断。
在调用阻塞方法时,会马上抛出InterruptException。blog
参考文章:多线程-interrupt(),isInterrupted(),interrupted() - 小路不懂2继承