CountDownLatch控制线程执行顺序


package com.dingwang.Thread;

import java.util.concurrent.CountDownLatch;

/**
 * 类FirstThread.java的实现描述:TODO 类实现描述
 * 
 * @author dingwang 2015年10月13日 下午4:01:06
 */
public class ThirdThread implements Runnable {

    private final CountDownLatch latch;

    public ThirdThread(CountDownLatch latch) {
        this.latch = latch;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    public void run() {
        System.out.println("the third thread is running!");
        //计算器-1
        latch.countDown();
        System.out.println("ThirdThread----------->count=" + latch.getCount());
    }

    public static void main(String[] args) throws InterruptedException {
        //FirstThread,SecondThread与ThirdThread实现完全相同
        //构造线程计数器
        final CountDownLatch latch = new CountDownLatch(3);
        Thread t1 = new Thread(new FirstThread(latch));
        Thread t2 = new Thread(new SecondThread(latch));
        Thread t3 = new Thread(new ThirdThread(latch));
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
        //线程计数器技术为0时,继续执行主线程
        latch.await();
        System.out.println("the main thread is End...");
    }
}

你可能感兴趣的:(多线程)