Interrupt ,给线程发送一个中断信号
给t1线程发送了中断信号,t1对线程的中断信号判断后,跳出循环,线程t1运行结束
public class Demo { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { System.out.println("t1 is running"); while (true) { System.out.println("#######"); if(Thread.currentThread().isInterrupted()) { break; } } }); t1.start(); try { Thread.sleep(1_000); t1.interrupt(); System.out.println("^^^"+t1.isInterrupted()); } catch (InterruptedException e1) { e1.printStackTrace(); } } }
wait和sleep和join都可以捕获InterruptException异常,清空中断信号。捕获异常后就不需要中断信号了,所以会清空中断信号
在异常处理代码块来根据业务决定是否跳出循环使线程结束。
wait
对wait的线程进行interrupt时候,线程会捕获interruptException
public class Demo1 { private static final Object MONITOR = new Object(); public static void main(String[] args) { Thread t = new Thread() { @Override public void run() { while (true) { synchronized (MONITOR) { System.out.println("=========>Before"); try { MONITOR.wait(); System.out.println("=========>Wait"); } catch (InterruptedException e) { System.out.println("###"+isInterrupted()); e.printStackTrace(); //e.printStackTrace(); } System.out.println("=========>After"); } } } }; t.start(); try { Thread.sleep(1_000); } catch (InterruptedException e1) { e1.printStackTrace(); } t.interrupt(); System.out.println("^^^"+t.isInterrupted()); } }
sleep
public class Demo2 { public static void main(String[] args) { Thread t = new Thread() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("###"+isInterrupted()); e.printStackTrace(); } } } }; t.start(); try { Thread.sleep(1_000); } catch (InterruptedException e1) { e1.printStackTrace(); } t.interrupt(); System.out.println("^^^"+t.isInterrupted()); } }
join
public class Demo3 { public static void main(String[] args) { Thread t = new Thread() { @Override public void run() { while (true) { } } }; t.start(); Thread main = Thread.currentThread(); Thread t2 = new Thread() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } main.interrupt(); System.out.println("interrupt"); } }; t2.start(); try { //这段代码是指t线程执行完后,再继续执行main线程, //这段代码是在main线程执行的,对main线程进行中断就会捕获异常 t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }