两阶段终止模式

 利用 isInterrupted


interrupt 可以打断正在执行的线程,无论这个线程是在 sleep,wait,还是正常运行。

当成功打断正在正常运行的线程时,线程的中断标记为true。

interrupt方法只是提醒该线程需要被停止,具体是否停止由操作系统决定。

可以使程序优雅的结束。

class TPTInterrupt {
        private Thread thread;
        public void start(){
            thread = new Thread(() -> {
                while(true) {
                    Thread current = Thread.currentThread();
                    if(current.isInterrupted()) {
                        log.debug("料理后事");
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                        log.debug("将结果保存");
                    } catch (InterruptedException e) {
                        current.interrupt();
                    }
// 执行监控操作
                }
            },"监控线程");
            thread.start();
        }
        public void stop() {
            thread.interrupt();
        }
    }

猜你喜欢

转载自blog.csdn.net/Mrrr_Li/article/details/121399639