Java多线程基础八 两阶段终止设计模式(Two Phase Termination)

两阶段终止设计模式是一种优雅的终止线程的方式。两阶段指的是一个线程发送终止另一个线程的请求,另一个线程接受到请求终止自身并做相应的处理。即两阶段指的是请求阶段和处理阶段。
Java多线程基础八 两阶段终止设计模式(Two Phase Termination)_第1张图片
比如我们要写一个系统监控程序,监控程序有死循环,每2s监控一次系统状况,没有中断的话会一直监控下去,如果有中断,就退出程序,并做一些保存工作。

public class SystemMonitor {
    private Thread monitor;

    public void start() {
        monitor = new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    Thread thread=Thread.currentThread();
                    if (thread.isInterrupted()) {
                        //
                        System.out.println("程序被中断,正在保存数据");
                        break;
                    }
                    try {
                        //可能中断1
                        Thread.sleep(1000);
                        //可能中断2
                        System.out.println("更新监控数据");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //异常中断,interrupt会被重置为false,在调用一遍使之变成true
                        thread.interrupt();
                    }
                }
            }
        });
        monitor.start();
    }

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

public class TwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException {
         SystemMonitor monitor=new SystemMonitor();
         monitor.start();
         Thread.sleep(5000);
         monitor.stop();
    }
}

两阶段终止设计模式的本质其实就是对中断的封装。这个设计模式的精髓就是catch 异常里面重新调用一遍interrupt方法。因为异常中断interrupt会被重置为false,在调用一遍使之变成true。不然,程序即使调用interrupt方法还是会进入死循环。

你可能感兴趣的:(多线程,两阶段终止,线程安全,中断处理,程序监控,清理工作)