测试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());
	}
}

阅读更多
换一批

没有更多推荐了,返回首页