@Slf4j
// 两阶段终止
public class TwoStageTerminationDemo {
public static void main(String[] args) throws InterruptedException {
TwoPhaseTermination demo = new TwoPhaseTermination();
demo.start();
Thread.sleep(1000);
demo.stop();
}
}
@Slf4j
class TwoPhaseTermination{
private Thread monitor;
// 启动线程
public void start(){
monitor = new Thread(()->{
while (true){
Thread current = Thread.currentThread();
if (current.isInterrupted()){
log.info("料理后事");
break;
}
try {
Thread.sleep(100);
log.info("监控程序");
} catch (InterruptedException e) {
e.printStackTrace();
// 因为异常会导致标记为false所以要重新设置打断标记
current.interrupt();
}
}
});
monitor.start();
}
public void stop(){
monitor.interrupt();
}
}
线程两阶段终止
最新推荐文章于 2024-07-22 14:15:06 发布