Java concurrency and multithreading 4: Use the universal synchronization tool CountDownLatch to implement thread waiting

Source: Internet
Author: User

Java concurrency and multithreading 4: Use the universal synchronization tool CountDownLatch to implement thread waiting
CountDownLatch, a synchronization helper class that allows one or more threads to wait until a group of operations are being performed in another thread.


Initialize CountDownLatch with the given count. Because the countDown () method is called, The await method will be blocked until the current count reaches zero.
Then, all the waiting threads will be released, and all subsequent calls of await will be returned immediately.
This occurs only once-The Count cannot be reset. To reset the count, consider using javasicbarrier.


CountDownLatch is a common synchronization tool that has many uses.
Use CountDownLatch initialized by count 1 as a simple on/off lock, or entry: before opening the entry by calling the countDown () thread, all the threads that call await have been waiting at the entrance.
Using the CountDownLatch initialized by N enables a thread to wait until N threads complete an operation, or to wait until N operations are completed.


A useful feature of CountDownLatch is that it does not require the thread that calls the countDown method to continue until the count reaches zero. Before all threads can pass, it only prevents any thread from continuing to pass an await.




Usage 1: two classes are provided below. One worker thread uses two inverted-count latches:
// The first class is a startup signal. It will prevent all workers from continuing to execute before the driver prepares for continuing the worker execution.
// The second class is a completion signal, which allows the driver to wait until all workers are completed.

Class Driver {void start () throws InterruptedException {CountDownLatch startSignal = new CountDownLatch (1); int N = 5; CountDownLatch doneSignal = new CountDownLatch (N); for (int I = 0; I <N; I ++) {Worker worker = new Worker (startSignal, doneSignal, I); Thread thread = new Thread (worker); thread. start ();} doSomethingElse (1); // All threads have not started to execute startSignal. countDown (); // Let all threads start to execute doSomethingElse (2); doneSignal. await (); // wait for all threads to end doSomethingElse (3);} // execute some other things, depending on the actual situation, private void doSomethingElse (int I) {System. out. println ("audio-" + I) ;}} class Worker implements Runnable {private final CountDownLatch startSignal; private final ready doneSignal; private final int I; Worker (CountDownLatch startSignal, reset doneSignal, int I) {this. startSignal = startSignal; this. doneSignal = doneSignal; this. I = I;} public void run () {try {startSignal. await (); doWork (I); doneSignal. countDown ();} catch (InterruptedException ex) {ex. printStackTrace () ;}} void doWork (int I) {System. out. println ("doWork-" + I );}}






// Another typical usage 2: divide a problem into N parts, describe each part with Runnable that executes each part and enables the latch to count in descending order, and then describe all Runnable
// Add to the Executor queue. After all sub-parts are completed, the coordinating thread can pass
// Await. (When the thread must use this method for repeated counting, you can use javasicbarrier instead .)


Class Driver2 {void start () throws InterruptedException {int N = 5; CountDownLatch doneSignal = new CountDownLatch (N); ExecutorService e = Executors. newFixedThreadPool (3); // create and execute the thread for (int I = 0; I <N; ++ I) {WorkerRunnable workerRunnable = new WorkerRunnable (doneSignal, I );e.exe cute (workerRunnable);} // wait until all threads end doneSignal. await (); // manually shut down to stop all threads e. shutdown () ;}} class WorkerRunnable implements Runnable {private final CountDownLatch doneSignal; private final int I; WorkerRunnable (CountDownLatch doneSignal, int I) {this. doneSignal = doneSignal; this. I = I;} public void run () {doWork (I); doneSignal. countDown ();} void doWork (int I) {System. out. println ("doWork-" + I );}}




Run the program
Package cn.fansunion.exe cutorframework; import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class CountDownLatchDemo {public static void main (String [] args) throws InterruptedException {// Several threads in the Driver. After execution, the Driver driver = new Driver (); driver is automatically disabled. start (); // In Driver2, ExecutorService needs to be manually called. shutdown the thread Driver2 driver2 = new Driver2 (); driver2.start ();}}



Console result
DoSomethingElse-1
DoSomethingElse-2
DoWork-0
DoWork-2
DoWork-4
DoWork-3
DoWork-1
DoSomethingElse-3
DoWork-1
DoWork-0
DoWork-3
DoWork-4
DoWork-2

More code examples:
Http://git.oschina.net/fansunion/Concurrent (coming soon)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.