高天乐 welcome you

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

字面翻译是“两阶段终止”,这个模式用来进行结束操作后,再终止线程。比如我们想停止一个线程,但是让他停止之前必须要做一些清理工作,这时候就需要用到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);
    }
}

 

 

posted on 2013-09-08 14:47  高天乐  阅读(383)  评论(0编辑  收藏  举报