Controlling multiple thread execution sequences using Countdownlatch

Source: Internet
Author: User
Tags thread class

Sometimes there is a need for multiple threads to work at the same time, and then several of them can be executed concurrently, but one thread needs to wait until the other threads have finished working before starting. For example, open multiple threads to download a large file, each thread only download a fixed section, and finally by another thread splicing all the fragments, then we can consider using Countdownlatch to control concurrency.

Countdownlatch is an auxiliary class provided by Java under the Java.util.concurrent package, which can be viewed as a counter, which maintains a count count internally, except that the operation of this counter is atomic, and only one thread can operate the counter, Coun Tdownlatch an initial count value is passed through the constructor, the caller can reduce the count by 1 by calling the Coundownlatch object's Cutdown () method, and if the await () method on the object is called, the caller will always be blocked here. Until someone else passes the Cutdown method, the count is reduced to 0 before the execution can continue.

ImportJava.util.concurrent.CountDownLatch; Public classSample {/*** counter, used to control thread * Incoming parameter 2, indicating counter count of 2*/    Private Final StaticCountdownlatch Mcountdownlatch =NewCountdownlatch (2); /*** Example worker thread class*/    Private Static classWorkingthreadextendsThread {Private FinalString Mthreadname; Private Final intMsleeptime;  PublicWorkingthread (String name,intsleeptime) {Mthreadname=name; Msleeptime=Sleeptime; } @Override Public voidrun () {System.out.println ("[" + Mthreadname + "] started!"); Try{thread.sleep (msleeptime); } Catch(interruptedexception e) {e.printstacktrace ();            } mcountdownlatch.countdown (); System.out.println ("[" + Mthreadname + "] end!"); }    }        /*** Sample Thread class*/    Private Static classSamplethreadextendsThread {@Override Public voidrun () {System.out.println ("[Samplethread] started!"); Try {                //will block here waiting for the count in Mcountdownlatch to become 0;//that is, wait for another Workingthread call Countdown ()mcountdownlatch.await (); } Catch(Interruptedexception e) {} System.out.println ("[Samplethread] end!"); }    }         Public Static voidMain (string[] args)throwsException {//First Run Samplethread        NewSamplethread (). Start (); //Run two worker threads//worker thread 1 runs for 5 seconds        NewWorkingthread ("WorkingThread1", 5000). Start (); //worker thread 2 runs for 2 seconds        NewWorkingthread ("WorkingThread2", 2000). Start (); }}
Operation Result:

[Samplethread] started!
[WorkingThread1] started!
[WorkingThread2] started!
[WorkingThread2] end!
[WorkingThread1] end!
[Samplethread] end!

achieved its purpose. Of course there are other ways to do this, and this article simply introduces a way to use Countdownlatch.

Controlling multiple thread execution sequences using Countdownlatch

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.