Thread.interrupt()简单从名称来看就是打断线程,那么到底是如何打断线程的,有什么限制条件?我们今天来讨论一下这个问题
首先我们看一下jdk上面的解释
If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}.
从代码上面的注释来看,如果在线程中由于Object.wait(),Thread.join()等方法造成阻塞,然后被打断,那么就会清除掉状态。因此我们猜测Thread.interrupt()向操作系统发出一个中断信号,设置中断标志,在操作系统合适的时候,检测中断标志,如果确实要求中断,那么就中断该线程。但是由于Object.wait()、Thread.join()的过程中该线程被中断,那么就会清除掉中断标志,那么就无法检测到相应中断标志,因此会导致该线程继续运行,接下来我们来进行验证:
public class InterrupteTest {
private static Thread thread = null;
public static void main(String args[]) throws InterruptedException {
thread = new Thread( new MyThread() );
thread.start();
Thread.sleep( 10 );
thread.interrupt();
System.out.println( "Interrupted Thread!" );
}
static class MyThread implements Runnable {
@Override
public void run() {
while (true) {
System.out.println( "I am running!" );
try {
Thread.sleep( 1000 );
} catch (InterruptedException e) {
}
}
}
}
}
当我们运行该程序的时候,我们会发现真的无法终止这个线程。那么我们如何真正终止该线程呢?
我们看下面的代码:
public class InterrupteTest {
private static Thread thread = null;
public static void main(String args[]) throws InterruptedException {
thread = new Thread( new MyThread() );
thread.start();
Thread.sleep( 10 );
thread.interrupt();
System.out.println( "Interrupted Thread!" );
}
static class MyThread implements Runnable {
@Override
public void run() {
while (!thread.isInterrupted()) {
System.out.println( "I am running!" );
try {
Thread.sleep( 1000 );
} catch (InterruptedException e) {
thread.interrupt();
}
}
}
}
}
运行上面的代码我们会发现上面,我们会发现线程正确的关闭了,当在线程睡眠的过程中,被打断后,会抛出InterruptedException,我们重新通过Thread.interrupt()重新设置线程的中断标志,那么线程在判断thread.isInterrupted()就会返回true了,自然就会退出线程了。