首页 > 代码库 > java中CountDownLatch线程同步的入门使用

java中CountDownLatch线程同步的入门使用

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

下面使用了两个倒计数锁存器:即一个等待另一个的完成

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


public class CountDownLatchTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
        ExecutorService ThreadPool = Executors.newCachedThreadPool();
        final CountDownLatch cdOrder = new CountDownLatch(1);
        final CountDownLatch cdAnswer = new CountDownLatch(3);
        for(int i=0;i<3;i++){
        	 Runnable runnable = new Runnable() {
     			
     			@Override
     			public void run() {
     				
     				try {
     					System.out.println("线程 " + Thread.currentThread().getName() + " 正在等待接受命令");
						cdOrder.await();
						System.out.println("线程 " + Thread.currentThread().getName() + " 已接受命令");
						Thread.sleep((long)Math.random()*10000);
						System.out.println("线程 " + Thread.currentThread().getName() + " 回应命令,处理结果");
						cdAnswer.countDown();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
     			}
     		};
     		ThreadPool.execute(runnable);
        }
        try {
			Thread.sleep((long)Math.random()*10000);
			System.out.println("线程 " + Thread.currentThread().getName() + " 正在等待发布命令");
			cdOrder.countDown();
			cdAnswer.await();
			System.out.println("线程 " + Thread.currentThread().getName() + " 已发布命令,正在等待结果");
			
			System.out.println("所有命令都处理完");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
       ThreadPool.shutdown();
	}

}



java中CountDownLatch线程同步的入门使用