两阶段终止模式-interrupt

420 阅读1分钟
 * 两阶段终止模式
 *    在一个线程t1中如何“优雅”终止线程t2?
 */
@Slf4j
public class Test4 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);
        tpt.stop();
    }

    @Slf4j
    static 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(2000);
                        log.info("执行监控记录");
                    } catch (InterruptedException e) {

                        log.info("线程被打断");
                        //在线程sleep时候被打断,会抛出异常;此时打断标记会重置为false; 所以此处重新设置打断标记
                        current.interrupt();
                    }
                }
            });
            monitor.start();
        }

        private void stop() {
            monitor.interrupt();
        }

    }
}