java

Concurrency with java

public class Driver {
	static int N = 10;

	public static void main(String[] args) throws InterruptedException {

		/*
		 * CountDownLatch ==>A synchronization aid that allows one or more
		 * threads to wait until a set of operations being performed in other
		 * threads completes. concurrency the start of other threads depend on
		 * the finish of another some threads
		 */

		/*
		 Example : lets we have worker that doSomething() firstly before all (10 threads) threads start
		 and after all threads finish he need to  doExtraSomething();
	   */
		
		CountDownLatch startSignal = new CountDownLatch(1);
		CountDownLatch doneSignal = new CountDownLatch(N);

		for (int i = 0; i < N; ++i)
			// create and start threads
			new Thread(new Worker(startSignal, doneSignal)).start();

		doSomething(); //  first run 
		startSignal.countDown(); // let all threads proceed signal await of all threads 
		doneSignal.await(); // wait for all to finish
		doExtraSomething();   //last run 
	}

	public static void doSomething() {
		System.out.println("Driver.doSomethingElse()");
	}

	public static void doExtraSomething() {
		System.out.println("Driver.doExtraSomethingElse()");
	}
}

public class Worker implements Runnable {
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;

	Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
	}

	public void run() {
		try {
			startSignal.await();//Causes the current thread to wait until the latch has counted down to zero. 
			doWork();
			doneSignal.countDown();//Decrements the count of the latch, releasing all waiting threads if the count reaches zero. 
		} catch (InterruptedException ex) {
		} // return;
	}

	void doWork() {
		System.out.println("Worker.doWork() Thread # "+doneSignal.getCount()  );
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s