官网解释
意思是当线程被blocked的时候可以被打断,wait()、sleep()、join()时被打断会抛出InterruptedException异常。
演示sleep()被打断
Thread t1 = new Thread() { @Override public void run() { while (true) { System.out.println("running..."); try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }; t1.start(); Thread.sleep(100L); System.out.println(t1.isInterrupted()); t1.interrupt(); System.out.println(t1.isInterrupted());
在sleep()被打断在异常中要执行break;打断循环,否则该循环一直在执行
演示wait()被打断
package com.dwz.concurrency.chapter6; public class ThreadInterrupt { private static final Object MONITOR = new Object(); public static void main(String[] args) throws InterruptedException { Thread t2 = new Thread() { @Override public void run() { while (true) { System.out.println("running..."); synchronized (MONITOR) { try { MONITOR.wait(100L); } catch (InterruptedException e) { System.out.println("收到打断信号。。。"); e.printStackTrace(); break; } } } } }; t2.start(); Thread.sleep(100L); System.out.println(t2.isInterrupted()); t2.interrupt(); System.out.println(t2.isInterrupted()); } }
1.跟sleep()一样,wait()被打断时在异常中要执行break;打断循环,否则该循环一直在执行
2.wait()的调用者一定是一个对象
演示join()被打断
package com.dwz.concurrency.chapter6; public class ThreadInterrupt3 { public static void main(String[] args) throws InterruptedException { Thread main = Thread.currentThread(); Thread t1 = new Thread() { @Override public void run() { while (true) { } } }; t1.start(); System.out.println("main: " + main.getName()); Thread t2 = new Thread() { @Override public void run() { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t2: " + Thread.currentThread().getName()); main.interrupt(); System.out.println("interrupt..."); } }; t2.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); t1.interrupt(); } System.out.println("main isInterrupted:" + main.isInterrupted()); System.out.println("t1 isInterrupted:" + t1.isInterrupted()); while(!t1.isInterrupted()) { Thread.sleep(1000L); System.out.println(t1.isInterrupted()); } } }
1.我们要清楚,join的对象是main线程,要想打断 t1.join(), 要在另一个线程中执行 main.interrupt()
2.isInterrupted()表示线程是否被打断,如果只执行 main.interrupt() 方法,意味着 t1.join()被打断,t1仍是未打断的,执行 t1.interrupt()才会改变t1状态
3. t1.join() 一定要在 t1.start() 和 t2.start() 之后被执行。