码迷,mamicode.com
首页 > 编程语言 > 详细

Java Concurrency - 浅析 CountDownLatch 的用法

时间:2016-06-01 23:12:27      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

CountDownLatch 是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

用给定的计数初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier。 

CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。

 

简单示例

package com.huey.hello.concurrency;

import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author  huey
 * @version 1.0 
 * @created 2015-2-28
 */
public class Worker implements Runnable {

    private String workerName;
    final private CountDownLatch doneSignal;
    
    public Worker(String workerName, CountDownLatch doneSignal) {
        this.workerName = workerName;
        this.doneSignal = doneSignal;
    }
    
    @Override
    public void run() {
        try {
            this.work();
            
            System.out.println(workerName + " has completed the job.");
            doneSignal.countDown();
        } catch (Exception e) {
        }
        
    }
    
    private void work() throws InterruptedException {
        System.out.println(workerName + " is working.");
        Thread.sleep(3000);
    }
}

测试

package com.huey.hello.concurrency;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author  huey
 * @version 1.0 
 * @created 2015-2-28
 */
public class Driver {
    
    static final int N = 3;    
    
    public static void main(String[] args) throws Exception {
        CountDownLatch doneSignal = new CountDownLatch(N);
        
        ExecutorService pool = Executors.newFixedThreadPool(N);
        for (int i = 1; i <= N; i++) {
            String workerName = "NO." + i;
            pool.execute(new Worker(workerName, doneSignal));
        }
        pool.shutdown();
        
        System.out.println("Waiting for all workers to complete their jobs.");
        doneSignal.await();
        
        System.out.println("All workers has completed their jobs.");
        System.out.println("Continue...");
    }
    
}

测试输出

NO.1 is working.
NO.2 is working.
Waiting for all workers to complete their jobs.
NO.3 is working.
NO.1 has completed the job.
NO.2 has completed the job.
NO.3 has completed the job.
All workers has completed their jobs.
Continue...

 

Java Concurrency - 浅析 CountDownLatch 的用法

标签:

原文地址:http://www.cnblogs.com/huey/p/5551142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!