CountDownLatchクラシックシミュレーション


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

public class CountDownLatchTest {

	//    100   ,10         ,        。          ,    。
	public static void main(String[] args) throws InterruptedException {

		//       
		final CountDownLatch begin = new CountDownLatch(1);

		//       
		final CountDownLatch end = new CountDownLatch(10);

		//     
		final ExecutorService exec = Executors.newFixedThreadPool(10);

		for (int index = 0; index < 10; index++) {
			final int NO = index + 1;
			Runnable run = new Runnable() {
				public void run() {
					try {
						//         ,        。
						//   
						begin.await();
						Thread.sleep((long) (Math.random() * 10000));
						System.out.println("No." + NO + " arrived");
					} catch (InterruptedException e) {
					} finally {
						//          ,end   
						end.countDown();
					}
				}
			};
			exec.submit(run);
		}
		System.out.println("Game Start");
		// begin  ,    
		begin.countDown();
		//   end  0,         
		end.await();
		System.out.println("Game Over");
		exec.shutdown();
	}
}