Created
May 26, 2016 20:46
-
-
Save anonymous/f58d5b5f25f40de43621d9362ae002e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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