目录:
- 线程中断的概念
- 中断的方法
- 总结
线程中断的概念:
线程中断是一种协作机制,它的执行并不是让线程真的中断,而是通知线程去中断。
就像有个小姐姐要加你好友,然后系统发了消息给你,加不加不还是取决于你自己嘛 φ(>ω<*) 。
中断的方法:
1、public static boolean interrupted();
判断线程是否处于中断状态,中断状态-true,非中断状态-false;若线程已中断则清除中断标识。
1 public class InterruptTest { 2 public static void main(String[] args) { 3 // 线程是否被中断 4 System.out.println("1: " + Thread.interrupted()); 5 // 设置线程中断 6 Thread.currentThread().interrupt(); 7 // 线程是否被中断 8 System.out.println("2: " + Thread.interrupted()); 9 // 线程是否被中断 10 System.out.println("3: " + Thread.interrupted()); 11 } 12 }
运行结果:
1: false 2: true 3: false
第4行代码,此时线程正常运行结果为false;第6行代码将当前主线程中断,所以第8行结果为true;紧接着interrupted()方法将中断标识清除,所以第10行结果为false。
2、public boolean isInterrupted();
判断线程是否处于中断状态,中断状态-true,非中断状态-false
1 public class IsInterruptedTest { 2 public static void main(String[] args) { 3 // 当前线程 4 Thread thread = Thread.currentThread(); 5 // 当前线程是否被中断 6 System.out.println("1: " + thread.isInterrupted()); 7 // 设置线程中断标识 8 thread.interrupt(); 9 // 判断线程是否被中断 10 System.out.println("2: " + thread.isInterrupted()); 11 // 判断线程是否被中断 12 System.out.println("3: " + thread.isInterrupted()); 13 try { 14 // 线程休眠 15 Thread.sleep(2000); 16 System.out.println("not interrupted..."); 17 } catch (Exception e) { 18 System.out.println("Thread.sleep interrupted..."); 19 // 判断线程是否被中断 20 System.out.println("4: " + thread.isInterrupted()); 21 } 22 System.out.println("5: " + thread.isInterrupted()); 23 } 24 }
运行结果:
1: false 2: true 3: true Thread.sleep interrupted... 4: false 5: false
12行前与interrupted同理,但不会清空中断标识,所以结果分别为false、true、true;因为线程已经中断,所以执行第15行的Thread.sleep(2000)时便会抛出InterruptedException异常,故打印Thread.sleep interrupted...;执行后中断状态清除,所以18、22行结果都是false(因为Thread.sleep()相当于对线程做出了响应,所有线程又没有中断了)。
3、public void interrupt();
将线程中断,并设置中断标识为true。
总结:
1、interrupt()方法是唯一能将中断状态设置为true的方法。
2、interrupted()方法会将当前线程的中断状态清除 。