最近在项目中遇到了线程中断得问题,需求如下:需要在线程被中断后及时做出相应,但是不知道线程何时被中断,因为线程中interrupt()方法只会把中断标识设置为false。
查阅资料后发现如下方法,做出分享。
public class RunAbleInterruptTest {
public void run() {
while (!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(500);
System.out.println("当前线程中断标试"+Thread.currentThread().isInterrupted());
}catch (InterruptedException e){
System.out.println("捕捉到当前线程中断标试"+Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
}
}
System.out.println("当前线程被中断:"+ Thread.currentThread().isInterrupted());
System.out.println("可在当前处响应线程被中断后操作");
}
public static void main(String[] args) throws InterruptedException{
Thread testThread=new Thread(new RunAbleInterruptTest());
testThread.start();
Thread.sleep(2000);
testThread.interrupt();
}
}
此处运用的是当线程在外部被中断后,再次调用sleep方法,会抛出InterruptedException,catch到异常以后在线程运行体中再次把当前线程中断,在while循环外部可处理当前线程被中断后的操作,这就是重新中断。
输出如下:
当前线程中断标试false
当前线程中断标试false
当前线程中断标试false
捕捉到当前线程中断标试false
当前线程被中断:true
可在当前处响应线程被中断后操作