How is CountDownLatch used in Java Multithreading? -
can me understand java countdownlatch
, when use it?
i don't have clear idea of how program works. understand 3 threads start @ once , each thread call countdownlatch after 3000ms. count down decrement 1 one. after latch becomes 0 program prints "completed". maybe way understood incorrect.
import java.util.concurrent.countdownlatch; import java.util.concurrent.executorservice; import java.util.concurrent.executors; class processor implements runnable { private countdownlatch latch; public processor(countdownlatch latch) { this.latch = latch; } public void run() { system.out.println("started."); try { thread.sleep(3000); } catch (interruptedexception e) { e.printstacktrace(); } latch.countdown(); } }
// -----------------------------------------------------
public class app { public static void main(string[] args) { countdownlatch latch = new countdownlatch(3); // coundown 3 0 executorservice executor = executors.newfixedthreadpool(3); // 3 threads in pool for(int i=0; < 3; i++) { executor.submit(new processor(latch)); // ref latch. each time call new processes latch count down 1 } try { latch.await(); // wait until latch counted down 0 } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("completed."); } }
yes, understood correctly. countdownlatch
works in latch principle, main thread wait until gate open. 1 thread waits n number of threads specified while creating countdownlatch
in java.
any thread, main thread of application, calls countdownlatch.await()
wait until count reaches 0 or interrupted thread. other thread required count down calling countdownlatch.countdown()
once completed or ready.
as count reaches zero, thread awaiting starts running. 1 of disadvantages/advantages of countdownlatch
it's not reusable once count reaches 0 can not use countdownlatch
more.
edit:
use countdownlatch
when 1 thread main thread, requires wait 1 or more thread complete, before can start processing.
classical example of using countdownlatch
in java server side core java application uses services architecture, multiple services provided multiple threads , application can not start processing until services have started successfully.
p.s. op's question has pretty straightforward example didn't include one.
Comments
Post a Comment