两阶段终止模式
两阶段终止模式
Two-Phase Termination Patter
描述:使监控线程优雅的终止其他正在运行的工作线程
代码实现:
class TwoPhaseTermination {
private Thread monitor;
public void start () {
monitor = new Thread(() -> {
while (true) {
Thread thread = Thread.currentThread();
if (thread.isInterrupted()) {
// TODO: 线程终止前的操作
System.out.println("Thread is interrupting...");
break;
}
try {
// TODO: 线程执行的业务代码
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
thread.interrupt();
}
}
System.out.println("Thread was interrupted");
}, "monitor");
monitor.start();
}
public void stop () {
monitor.interrupt();
}
}
测试代码:
public class TwoPhaseTerminationTest {
public static void main(String[] args) {
TwoPhaseTermination pattern = new TwoPhaseTermination();
pattern.start();
try {
TimeUnit.SECONDS.sleep(2);
pattern.stop();
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
本作品采用《CC 协议》,转载必须注明作者和本文链接