測試CountDownLatch和任務數量相同的線程並行

public class TestCountDownLatch {

	public static void main(String[] args) throws InterruptedException {
		
		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		CountDownLatch doneSignal = new CountDownLatch(5);

		for (int i = 0; i < 5; ++i) // create and start threads
			threadPool.execute(new WorkerRunnable(doneSignal, i));

		doneSignal.await(); // wait for all to finish
		System.out.println("-----------");

		threadPool.shutdown();
	}
}

class WorkerRunnable implements Runnable {
	
	private final CountDownLatch doneSignal;
	private final int i;

	WorkerRunnable(CountDownLatch doneSignal, int i) {
		this.doneSignal = doneSignal;
		this.i = i;
	}

	public void run() {
		try {
			doWork(i);
			doneSignal.countDown();
		} catch (Exception ex) {
		} // return;
	}

	void doWork(int i) {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("===========" + Thread.currentThread().getName());
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章