使用CountDownLatch做线程同步

/ CountDownLatch多线程Java技术 / 没有评论 / 1607浏览

CountDownLatch

源码的说明如下

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。

CountDownLatch的用法

  1. 用法一:CountDownLatch典型用法某一线程在开始运行前等待n个线程执行完毕。将CountDownLatch的计数器初始化为n new CountDownLatch(n) ,每当一个任务线程执行完毕,就将计数器减1 countdownlatch.countDown(),当计数器的值变为0时,在CountDownLatch上 await() 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。

  2. 用法二:实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。做法是初始化一个共享的CountDownLatch(1),将其计数器初始化为1,多个线程在开始执行任务前首先 coundownlatch.await(),当主线程调用 countDown() 时,计数器变为0,多个线程同时被唤醒。

CountDownLatch的不足

CountDownLatch是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。

主要的几个方法

1.构造器

public CountDownLatch(int count) {  };  //参数count为计数值

2.其他相关方法

public void await() throws InterruptedException { };   //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public void countDown() { };  //将count值减1

使用示例

    @Test
    public void testCountDownLatch() {
        CountDownLatch latch = new CountDownLatch(2);
        ExecutorService executorService = new ThreadPoolExecutor(2, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Sub thread 1: " + Thread.currentThread().getName() + " running ... ");
                    Thread.sleep(4000);
                    System.out.println("Sub thread 1: " + Thread.currentThread().getName() + " completed");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Sub thread 2: " + Thread.currentThread().getName() + " running ... ");
                    Thread.sleep(1000);
                    System.out.println("Sub thread 2: " + Thread.currentThread().getName() + " completed");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        });

        try {
            System.out.println("Waiting two sub thread ...");
            latch.await();
            System.out.println("Sub thread all donne");
            System.out.println("Continuing main thread");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Waiting two sub thread ...
Sub thread 2: pool-1-thread-2 running ... 
Sub thread 2: pool-1-thread-2 completed
Sub thread 1: pool-1-thread-1 completed
Sub thread all donne
Continuing main thread