多线程设计模式:两阶段终止模式

流程图:

第一版(后续会优化)

@Slf4j
public class TwoPhaseTermination {

    private Thread monitor;

    public void start(){
        monitor = new Thread(()->{
            Thread current = Thread.currentThread();
            while(true){

                if(current.isInterrupted()){
                    log.info("after handler");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.info("monitor");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    current.interrupt();
                }
            }

        });
        monitor.start();
    }

    public void stop(){
        monitor.interrupt();
    }
}
class Inner{
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination termination = new TwoPhaseTermination();
        termination.start();
        TimeUnit.SECONDS.sleep(5);
        termination.stop();
    }
}

原文地址:https://www.cnblogs.com/wwjj4811/p/13671674.html