字面翻译是“两阶段终止”,这个模式用来进行结束操作后,再终止线程。比如我们想停止一个线程,但是让他停止之前必须要做一些清理工作,这时候就需要用到two-phase termination模式。
public class TwoPhaseTerminationTest { /** * @param args */ public static void main(String[] args) { System.out.println("main begin"); try { CountupThread t = new CountupThread(); t.start(); Thread.sleep(10000); System.out.println("main: shutdownRequest"); t.shutdownRequest(); System.out.println("main: join"); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main end"); } } class CountupThread extends Thread { private long counter = 0; private volatile boolean shutdownReuqest = false; public void shutdownRequest() { this.shutdownReuqest = true; interrupt(); } public boolean isShutdownRequested() { return shutdownReuqest; } @Override public void run() { try { while (!shutdownReuqest) { doWork(); } } catch (InterruptedException e) { } finally { doShutdown(); } } private void doShutdown() { System.out.println("doShutdown: count=" + counter); } private void doWork() throws InterruptedException { counter++; System.out.println("doWork: count=" + counter); Thread.sleep(500); } }