1. 程式人生 > >CountDownLatch 執行緒等待例項

CountDownLatch 執行緒等待例項

package com.sgcc.test;

import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;

public class test {

public static void main1(String[] args) {
	ThreadPoolExecutor poolExe = new ThreadPoolExecutor(100, 1000, 1, TimeUnit.SECONDS,
		    new LinkedBlockingDeque<Runnable>(100));
	// 考試開始鈴聲響起,考試開始
	final CountDownLatch examBegin = new CountDownLatch(1);
	// 單個考生,考試結束交卷
	final CountDownLatch student = new CountDownLatch(9);

	// 一個考場10位考生
	for (int i = 0; i < 10; i++) {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					System.out.println("考生" + Thread.currentThread().getName() + "在等待考試開始的鈴聲響起");
					examBegin.await();
					System.out.println("考生聽到鈴聲" + Thread.currentThread().getName() + "開始答題");
					long time = (long) (Math.random() * 100);
					Thread.sleep(time);//答題過程,真正的業務邏輯處理部分
					System.out.println("考生" + Thread.currentThread().getName() + "交卷,答題耗時:"+time);
					student.countDown();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		poolExe.execute(runnable); // 運動員開始任務
	}

	try {
		// 答題時間
		Thread.sleep((long) (Math.random() * 10000));
		System.out.println("考場" + Thread.currentThread().getName() + "開始鈴聲即將響起");
		examBegin.countDown(); // 命令計數器置為0
		System.out.println("考場" + Thread.currentThread().getName() + "考試開始鈴聲響起");
		student.await(); // 所有考生交卷
		System.out.println("考場" + Thread.currentThread().getName() + "考試結束");
	} catch (Exception e) {
		e.printStackTrace();
	}
	poolExe.shutdown();

}

}