Skip to content

Instantly share code, notes, and snippets.

Created May 26, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/f58d5b5f25f40de43621d9362ae002e1 to your computer and use it in GitHub Desktop.
Save anonymous/f58d5b5f25f40de43621d9362ae002e1 to your computer and use it in GitHub Desktop.
public class App {
public static void main(String[]args){
//CountDownLatch, is a thread safe class
//A synchronization aid that allows one or more threads
//to wait until a set of operations being performed in other threads completes.
//CountDownLatch(int count)
CountDownLatch latch=new CountDownLatch(1);
//A CountDownLatch is initialized with a given count.
//The await methods block until the current count reaches zero
ExecutorService exc=Executors.newFixedThreadPool(3);
for(int i=0;i<3;i++){
//creates three threads, each one gets a latch
exc.submit(new Processor(latch));
}
try {
// Causes the current thread to wait until the latch has counted down to zero,
//unless the thread is interrupted, or the specified waiting time elapses.
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Completed");
}
}
class Processor implements Runnable{
private CountDownLatch latch;
public Processor(CountDownLatch latch){
this.latch=latch;
}
@Override
public void run() {
System.out.println("Started...");
try{
//After three seconds each one will call countDown
Thread.sleep(300);
}catch(Exception e){
}
//countDown
//Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
//every time countDown is called, the value specified, will be counted down by 1
latch.countDown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment