1. 程式人生 > 實用技巧 >多執行緒設計模式:兩階段終止模式

多執行緒設計模式:兩階段終止模式

流程圖:

第一版(後續會優化)

@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();
    }
}