首页 > 代码库 > java并发之CountDownLatch

java并发之CountDownLatch

java.util.conccurent包中有很多关于并发中可能会使用到的工具类,本文的主角CountDownLatch就是其中之一,其实CountDownLatch就是一个计数器,在它的计数值变为0之前,它的await方法会阻塞当前线程的执行。

构造函数

CountDownLatch只有一个构造函数,这个函数接受一个int类型的参数,这个参数的意义就是计数器的计数值,如果你想在程序中获得一个CountDownLatch的实例,你可以:

CountDownLatch countDownLatch = new CountDownLatch(1);

如何使用

import java.util.concurrent.CountDownLatch;

/**
 * Filename : Child.java
 * Created by Derekxyz on 2014/7/18.
 */
public class Child implements Runnable{

    private CountDownLatch c1;

    public Child(CountDownLatch c1) {
        this.c1 = c1;
    }

    public void run() {

        try {
            System.out.println("i`m child,i want to eat");
            c1.await();
            System.out.println("oh ,it`s very delicious!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);//实例化一计数值为1的计数器
        Thread t = new Thread(new Child(latch));
        t.start();//会输出i`m child,i want to eat,然后等待计数器的值归零
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("now it`s time to eat");
        latch.countDown();//将计数值减一,即变为0 

        //线程中的下一句话oh ,it`s very delicious!,此刻将会输出。


    }
}

上面一段代码简单的介绍了CountDownLatch的使用方法。