CountDownLatch就是个倒计的计数器,用法如下:

package com.concurrent;

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

import junit.framework.TestCase;

public class TestCountDownLatch extends TestCase {
	private final int COUNT = 10;

	public void testCountDownLatch() {
		final CountDownLatch cdl = new CountDownLatch(COUNT);
		final Random random = new Random();
		ExecutorService executorService = Executors.newFixedThreadPool(COUNT);
		for (int i = 0; i < COUNT; i++) {
			final int index = i + 1;
			Runnable r = new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("begin to work " + index);
						Thread.sleep(random.nextInt(10) * 1000);
						System.out.println("end " + index);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						cdl.countDown();
					}
				}
			};
			executorService.submit(r);
		}
		try {
			cdl.await();
			System.out.println("testCountDownLatch");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executorService.shutdown();
	}
}




总共有11个线程,主线程里生成了10个线程,主线程等10个线程全部运行结束后,再输出testCountDownLatch

运行结果如下:

begin to work 1
begin to work 3
begin to work 2
begin to work 5
begin to work 6
begin to work 4
end 4
begin to work 7
begin to work 8
begin to work 9
begin to work 10
end 9
end 3
end 1
end 7
end 2
end 10
end 8
end 5
end 6
testCountDownLatch