CountDownLatch 2

 

 
package com.ls.java_concurrency.countdownlatch;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Another typical usage would be to divide a problem into N parts,
 * describe each part with a Runnable that executes that portion and
 * counts down on the latch, and queue all the Runnables to an
 * Executor.  When all sub-parts are complete, the coordinating thread
 * will be able to pass through await. (When threads must repeatedly
 * count down in this way, instead use a CyclicBarrier.)
 * @author astute_sparrow
 * ------Driver------
 */
public class CountDownLatchAnotherDemo {
	
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch doneSignal = new CountDownLatch(10);
		final BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>();
		final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 600, 30,
				TimeUnit.SECONDS, queue, Executors.defaultThreadFactory(),
				new ThreadPoolExecutor.AbortPolicy());
		for(int i=0; i<20; i++)
			executor.execute(new WorkerRunnable(doneSignal, 1));
		System.out.println("Main Thread starts......");
		Thread.sleep(10000);
		doneSignal.await();
		System.out.println("All sub thread ends!!!");
	}
	
}

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() {
		doWork(i);
		doneSignal.countDown();
	}
	
	void doWork(int i) {
		System.out.println("......doWork......" + Thread.currentThread());
	}
}
 

 

 

你可能感兴趣的:(java,thread)