Wednesday, July 1, 2015

CountDownLatch Example in Java

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class CountDownLatchExample {

public static void main(String args[]) {

final CountDownLatch latch = new CountDownLatch(2);
// Sharedresource sr = new Sharedresource(semaphore);
Thread t1 = new Thread(new ThreadCreated("First", latch));
Thread t2 = new Thread(new ThreadCreated("Second", latch));

t1.start();
t2.start();

try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(" Both threads are Up and Running");

}

}

class ThreadCreated implements Runnable {
// CommonResources cr = new CommonResources();

private final CountDownLatch latch;
private final String name;

ThreadCreated(String name, CountDownLatch latch) {
this.latch = latch;
this.name = name;
}

public void run() {
synchronized (ThreadCreated.class) {
System.out.println(" Count is " + latch.getCount());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" Thread to get ready "
+ Thread.currentThread().getName());
latch.countDown();
System.out.println(" Count  of latch after countdown is "
+ latch.getCount());
}
}
}

Output will be:
 Count is 2
 Thread to get ready Thread-0
 Count  of latch after countdown is 1
 Count is 1
 Thread to get ready Thread-1
 Count  of latch after countdown is 0
 Both threads are Up and Running


NOTE: CountDownLatch simply allows the particular thread to execute after the countDownLatch count has reached ZERO, nothing to do with the syncronization, hence Syncronized block jumps in.Here Lock is Class level Lock since the Thread are two different instances.


Synchronization can alternatively be acheived using Lock as:
Replace
//synchronized (ThreadCreated.class) {
}
with
 final Lock lock = new ReentrantLock();
 lock.lock();
 lock.unlock();




No comments:

Post a Comment