调用interrupt(),通知线程应该中断:
1 如果线程处于阻塞状态,则线程立即退出被阻塞状态,并抛出一个InterruptedException异常;
2 如果线程处于正常活动状态,那
package com.mall.controllor.alene;
import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl;
/**
* Created by 60341 on 2020/3/18.
*/
public class InterruptDemo {
/*
interrupt() 其作用是中断此线程(此线程不一定是当前线程,而是指调用该方法的Thread实例所代表的线程),但实际上只是给线程设置一个中断标志,线程仍会继续运行。
*/
public static void main(String[] args) throws InterruptedException {
Runnable interruptTask = new Runnable() {
@Override
public void run() {
int i = 0;
try {
//在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程
while(!Thread.currentThread().isInterrupted()){
Thread.sleep(100);
i++;
System.out.println("CurrentThread name is " + Thread.currentThread().getName() + ";CurrentThread status is " + Thread.currentThread().getState() + " loop "+ i);
}
} catch (InterruptedException e) {
//在调用阻塞方法时,正确处理InterruptedException异常,在catch异常后就结束线程。
System.out.println("CurrentThread name is " + Thread.currentThread().getName() + ";CurrentThread status is " + Thread.currentThread().getState()+ " catch InterruptedException");
}
}
};
Thread t1 = new Thread(interruptTask,"t1");
System.out.println(t1.getName()+" "+ t1.getState() + " is new");
t1.start();
System.out.println(t1.getName()+" "+ t1.getState() + " is started");
//主线程休眠300ms,主线程给t1发中断指令;
Thread.sleep(300);
//t1线程收到中断命令,isInterrupted()置为false,while(!Thread.currentThread().isInterrupted())立刻被检测到,如果在阻塞状态,则抛出异常被catch处理。如果是正常运行,只将阻塞标志置为true,线程继续进行,不影响下面操作。
t1.interrupt();
System.out.println(t1.getName()+" "+ t1.getState() + " is interrupted");
//主线程休眠300ms,查看t1状态;
Thread.sleep(300);
System.out.println(t1.getName()+" "+ t1.getState() + " is interrupted now");
}
/*输出:
t1 NEW is new
t1 RUNNABLE is started
CurrentThread name is t1;CurrentThread status is RUNNABLE loop 1
CurrentThread name is t1;CurrentThread status is RUNNABLE loop 2
t1 TIMED_WAITING is interrupted
CurrentThread name is t1;CurrentThread status is RUNNABLEcatch InterruptedException
t1 TERMINATED is interrupted now
*/
}
么该线程的中断标志设为true,被设置中断标志的线程将继续正常运行,不受影响。