两阶段终止模式
package com.ceci.thread;
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "mode.TwoPhaseTerminationMode")
public class TwoPhaseTerminationMode {
public static void main(String[] args) throws InterruptedException {
TwoPhaseTerminationMethod thread = new TwoPhaseTerminationMethod();
thread.start();
Thread.sleep(3500);
thread.stop();
}
}
@Slf4j(topic = "mode.TwoPhaseTerminationMethod")
class TwoPhaseTerminationMethod{
private Thread monitor;
public void start(){
monitor = new Thread(() -> {
while(true){
boolean flag = Thread.currentThread().isInterrupted();
if (flag){
log.info("当前 interrupt status:{}",Thread.currentThread().isInterrupted());
log.info("打断后。。。");
break;
}
try {
log.info("当前 interrupt status:{}",Thread.currentThread().isInterrupted());
log.info("继续执行监测");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
});
monitor.start();
}
public void stop(){
monitor.interrupt();
}
}