Book01-No.十 Two-Phase Termination Pattern
Book01-No.10 Two-Phase Termination Pattern
1、你正在执行一个操作的时候,另一个线程发出中断的请求,你接受到这个请求,停止执行操作,并不是马上结束,进入准备中断状态,等中断结束后退出。
2、执行流程:开始----执行作业中--------终止要求 ---------------终止处理中 --------------终止结束完毕-----------结束
3、处理的关键:
- 安全的结束(安全性)
- 一定会进行终止处理(生命性)
- 收到终止请求后要尽快进行终止处理(有效性)
4、程序设计
package com.metarnet.TwoPhaseTerminationPattern; /** * 请求类 * @author Administrator * */ public class Main { public static void main(String[] args) { CountupThread thread1 = new CountupThread(); CountupThread thread2 = new CountupThread(); thread1.start(); thread2.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("main start end.."); thread1.shutdown(); // thread2.shutdown(); System.out.println("main join"); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package com.metarnet.TwoPhaseTerminationPattern; /** * 处理类 * @author Administrator * */ public class CountupThread extends Thread { private long count = 0; private volatile boolean isShutdownRequested = false; // 终止请求 public void shutdown() { isShutdownRequested = true; this.interrupt(); } public boolean isShutdownRequested() { return isShutdownRequested; } public void setShutdownRequested(boolean isShutdownRequested) { this.isShutdownRequested = isShutdownRequested; } @Override public void run() { try { while(!isShutdownRequested) { doWork(); } } catch (InterruptedException e) { isShutdownRequested = true; } finally { diFinally(); } } private void diFinally() { System.out.println(Thread.currentThread().getName() + "finsh doWork count = " + count); } private void doWork() throws InterruptedException { count++; System.out.println(Thread.currentThread().getName() + "doWork count = " + count); Thread.sleep(500); } }