1、概念java
java中线程有开始,运行(就绪,运行),阻塞,等待,终止这几种状态。其中在等待的时候能够经过设置中断标志位来唤醒线程。通常状况下等待状态的线程检查到中断标志被置位,则会抛出InterruptedException异常,捕获异常,复位中断标志,能够使线程继续运行。
ide
thread.interrupt() 设置中断标识位线程
Thread.interrupt() 回复中断标识位code
thread.isInterrupted() 返回中断标识位get
什么状况下能够使用Interrunptit
(1)若是线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程当中受阻,则其中断状态将被清除,它还将收到一个InterruptedException异常。这个时候,咱们能够经过捕获InterruptedException异常来终止线程的执行,具体能够经过return等退出或改变共享变量的值使其退出。io
(2)若是该线程在可中断的通道上的 I/O 操做中受阻,则该通道将被关闭,该线程的中断状态将被设置而且该线程将收到一个 ClosedByInterruptException。这时候处理方法同样,只是捕获的异常不同而已。class
2、代码thread
public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(1000); } catch (InterruptedException e) { System.out.println(e.getStackTrace()); System.out.println("thread is interrupt ? >>> " + Thread.currentThread().isInterrupted()); Thread.currentThread().interrupt(); System.out.println("thread is interrupt ? >>> " + Thread.currentThread().isInterrupted()); } } }); thread.start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { } thread.interrupt(); }
输出结果:变量
[Ljava.lang.StackTraceElement;@1e0c386d
thread is interrupt ? >>> false
thread is interrupt ? >>> true