中断线程

当对一个线程调用interrupt方法时,线程的中断状态将被置位。这是每一个线程都具有的boolean标志。

interrupt

中断线程。

1 public void interrupt()

测试当前线程是否已经中断。

interrupted:

1 public static boolean interrupted()

  线程的中断状态 由该方法清除。

测试线程是否已经中断。

isInterrupted:

1 public boolean isInterrupted()

 线程的中断状态 不受该方法的影响。

注释:

1.在catch子句中调用Thread.currentThread().interrupt()来设置中断状态。于是,调用者可以对其进行检测。

1 void mySubTask()
2 {
3 ...
4   try{sleep(delay);}
5 catch(InterruptedException e){Thread.currentThread().interrupt();}
6 ...  
7 }

或者,更好的选择是,用throws InterruptedException标记方法,不采用try语句块捕获异常。于是,调用者(或者,最终的run方法)可以捕获这一异常。

1 void mySubTask() throws InterruptException
2 {
3 ...
4 sleep(delay);
5 ...
6 }
原文地址:https://www.cnblogs.com/linst/p/5619894.html