Countdownlatch lock in Java concurrent programming for multiple threads to start running at the same time or the main thread to wait for a child thread to end

Source: Internet
Author: User

Java 5 introduced the Concurrent concurrency package inside the Countdownlatch can actually think of it as a counter, but the operation of this counter is atomic operation, while only one thread to operate the counter, That is, you can only have one thread at a time to reduce the value of this counter. A very typical application scenario for Countdownlatch is that there is one task that wants to go down, but it must wait until the other tasks have been completed before proceeding. If we want to continue down the task of calling an await () method for a Countdownlatch object, the other task executes its own task and calls the countdown () method on the same Countdownlatch object, which calls await () The task of the method will block waiting until the count of the Countdownlatch object is reduced to 0. Therefore, the Countdownlatch class can be used to control when multiple threads start running at the same time, or for the main thread to wait for all child threads to end.
For example, there are three workers working for the boss, and the boss has a habit of checking the work of all the workers when three workers have finished the day's work. Remember this condition: Three workers finish all the work first, and the boss checks. So here in Java code Design two classes, the worker on behalf of workers, bosses on behalf of the boss, the specific code implementation is as follows:

1  Public classWorkerImplementsrunnable{2        3     PrivateCountdownlatch Downlatch; 4     PrivateString name; 5        6      PublicWorker (Countdownlatch downlatch, String name) {7          This. Downlatch =Downlatch; 8          This. Name =name; 9     }   Ten        One      Public voidrun () { A          This. DoWork ();  -         Try  - {    theTimeUnit.SECONDS.sleep (NewRandom (). Nextint (10));  -}Catch(Interruptedexception IE) { -         }    -System.out.println ( This. Name + "It's done!" ");  +          This. Downlatch.countdown ();  -             +     }    A         at     Private voiddoWork () -     {    -System.out.println ( This. name + "Working!");  -     }    -         - }  in  -================== to  +  Public classBossImplementsRunnable { -    the     PrivateCountdownlatch Downlatch;  *         $      PublicBoss (Countdownlatch downlatch) {Panax Notoginseng          This. Downlatch =Downlatch;  -     }    the         +      Public voidrun () { ASYSTEM.OUT.PRINTLN ("The Boss is waiting for all the workers to finish the job ...");  the         Try {    +              This. downlatch.await ();  -}Catch(interruptedexception e) { $         }    $SYSTEM.OUT.PRINTLN ("The workers have finished their work, the boss began to check!") ");  -     }    -    the }  - Wuyi  the============================ -    Wu  Public classCountdownlatchdemo { -    About      Public Static voidMain (string[] args) { $Executorservice executor =Executors.newcachedthreadpool ();  -             -Countdownlatch latch =NewCountdownlatch (3);  -             AWorker W1 =NewWorker (Latch, "Zhang San");  +Worker W2 =NewWorker (Latch, "John Doe");  theWorker W3 =NewWorker (Latch, "Wang er");  -             $Boss Boss =NewBoss (latch);  the             the Executor.execute (W3);  the Executor.execute (W2);  the Executor.execute (W1);  - Executor.execute (Boss);  in             the Executor.shutdown ();  the     }     About}

Countdownlatch lock in Java concurrent programming for multiple threads to start running at the same time or the main thread to wait for a child thread to end

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.