1、首先大家应该知道sleep()、wait()、join()调用者三个方法可以使得线程阻塞,线程阻塞之后,cpu是不会分配时间片的。
2、interrupt()方法:
作用:打断线程。
1、打断处于阻塞状态的线程。
2、打断正在运行的线程。
注意:
1、当使用interrupt()方法去打断处于阻塞状态的线程时,会以异常的方式打印,而不会更新打断标记,因此,虽然被打断,但是打断标记依然为false。
2、当使用interrupt()方法去打断正在运行线程时,被打断的线程会继续运行,但是该线程的打断标记会更新,更新为true,因此可以根据打断标记来作为判断条件使得线程停止。
这里不得不说的多线程的一个设计模式——两阶段终止模式
/**
* 两阶段终止模式
* @author
* @since 2021/9/28
**/
@Slf4j
public class TestMain {
public static void main(String[] args) throws InterruptedException {
ThreadTest threadTest = new ThreadTest();
threadTest.start();
Thread.sleep(3000);
threadTest.stop();
}
}
@Slf4j
class ThreadTest{
private Thread thread;
/**
* 监控线程启动
*/
public void start(){
thread= new Thread(()-> {
while(true){
//获取当前线程
Thread current = Thread.currentThread();
//判断监控线程是否被打断
if (current.isInterrupted()){ //isInterrupted判断完后不会清除打断标记,但是interrupted方法判断完后会清除
log.debug("处理善后");
break;
}
try {
Thread.sleep(1000); //打断情况1:会进入异常
log.debug("监控继续执行");//打断情况2:不会进入异常
} catch (InterruptedException e) {
e.printStackTrace();
//如果是在睡眠的时候被打断,那么会进入catch,而且打断状态不会更新,所以才重新设置打断标记
current.interrupt();
}
}
});
thread.start();
}
/**
* 停止监控线程
*/
public void stop(){
thread.interrupt();
}
}
部分注释使用了行尾注释,为了大家方便理解,真正开发中使用行尾注释是不规范的。