title: Java设计模式
date: 2022-1-9 10:17:20
tags: 设计模式
categories: Java
cover: imgcat/java.png
1. 两阶段终止模式
终止模式之两阶段终止模式:Two Phase Termination
目标:在一个线程 T1 中如何优雅终止线程 T2?优雅指的是给 T2 一个后置处理器
错误思想:
- 使用线程对象的 stop() 方法停止线程:stop 方法会真正杀死线程,如果这时线程锁住了共享资源,当它被杀死后就再也没有机会释放锁,其它线程将永远无法获取锁
- 使用 System.exit(int) 方法停止线程:目的仅是停止一个线程,但这种做法会让整个程序都停止
两阶段终止模式图示:
/*** 优雅的打断正在运行的线程*/public static void test02(){Monitor monitor = new Monitor();monitor.start();sleep(1000);monitor.stop();}class Monitor{private Thread monitor;public void start(){// 监控器线程monitor = new Thread(() -> {// 开始不停得到监控while(true){// 判断当前线程是否被打断if(Thread.currentThread().isInterrupted()){System.out.println("料理后事...");break; // 结束循环}System.out.println("监控器运行中...");// 睡眠2s,不需要一直监控try {Thread.sleep(2000);System.out.println("执行监控记录...");} catch (InterruptedException e) {e.printStackTrace();// 如果线程在睡眠时被打断,打断标记被设置为false,需要手动设置为trueThread.currentThread().interrupt();}}}, "monitor");monitor.start();}// 停止监控线程public void stop(){monitor.interrupt();}}
