提示:以下是本篇文章正文内容,下面案例可供参考
一、两阶段终止模式是什么?
在一个线程T1中如何优雅的终止线程T2?这里的【优雅】指的是给T2一个料理后事的机会
二、错误思路
使用线程对象的stop()方法停止线程
1.stop方法会真正杀死线程,如果这时线程锁住了共享资源,
那么它被杀死后就再也没有机会释放锁,其他线程将永远无法获取锁
使用System.exit(int)方法停止线程
1.目的仅是停止一个线程,但这种做法会让整个程序都停止
三、正确演示
在线程睡眠过程中,出现被打断,则会走catch报错语句块
public class App {
public static void main(String[] args) throws Exception {
Test test = new Test();
test.start();
Thread.sleep(3000);
test.stop();
}
}
class Test {
private Thread monitor;
//启动线程监控
public void start() {
monitor = new Thread(() -> {
while (true) {
Thread thread = Thread.currentThread();
if (thread.isInterrupted()) {
System.out.println("程序终止");
break;
}
try {
Thread.sleep(1000);
//情况1,当睡眠过程中出现打断,则会走catch语句块,thread.isInterrupted()的结果置位false
System.out.println("执行监控记录");
//情况2,当这种情况下被打断,thread.isInterrupted()是true,则不需要手动设置
} catch (InterruptedException e) {
e.printStackTrace();
//重新设置打断标记
monitor.interrupt();
}
}
});
monitor.start();
}
//停止监控线程
public void stop() {
monitor.interrupt();
}
}
总结
完