Java thread (11): CountDownLatch-concurrent thread issuing gun

Source: Internet
Author: User

During the-meter sprint of the Track and Field Competition, the athletes will prepare for the action at the starting line. When the starting gun makes a sound, the athletes will struggle to run. During multi-thread running, there is also such a issuing gun -- CountDownLatch, which controls the thread running by controlling the predefined count.
The CountDownLatch construction method is as follows:
[Java] view plaincopy
CountDownLatch (int count); // construct a CountDownLatch initialized with a given count.

The main methods used are:
[Java] view plaincopy
Void await (); // keep the current thread waiting until the latch is counted to zero, unless the thread is interrupted.
Boolean await (long timeout, TimeUnit unit); // keep the current thread waiting until the latch is counted to zero, unless the thread is interrupted or exceeds the specified waiting time.
Void countDown (); // decrease the Count of latches. If the Count reaches zero, all waiting threads are released.
Long getCount (); // returns the current count.
String toString (); // returns the String that identifies the lock and its status.

CountDownLatch is a synchronization helper class that allows one or more threads to wait until a group of operations are performed in another thread. You can call the countDown () method to initialize CountDownLatch for a given count. The await () method is blocked until the current count reaches zero. When the Count reaches zero, all waiting threads will be released, and all subsequent calls to await () will be returned immediately. However, this phenomenon only occurs once-The Count cannot be reset. If you need to reset the count, consider using javasicbarrier.
CountDownLatch is a common synchronization tool that has many uses. CountDownLatch initialized with count as 1 can be used as a simple ON/OFF latch or entry, in the countDown () by calling () before opening the entrance, 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 await (). It has more flexibility than javasicbarrier. It can control threads with uncertain numbers, rather than threads like javasicbarrier in determining the number of threads wait () only when the countDown () value is 0 Can All threads pass through.
The following is an example:
[Java]
Public class CountdownLatchTest {
Public static void main (String [] args ){
ExecutorService service = Executors. newCachedThreadPool ();
Final CountDownLatch cdOrder = new CountDownLatch (1 );
Final CountDownLatch cdAnswer = new CountDownLatch (3 );
For (int I = 0; I <3; I ++ ){
Runnable runnable = new Runnable (){
Public void run (){
Try {
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Preparing to accept the command ");
CdOrder. await ();
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Commands accepted ");
Thread. sleep (long) (Math. random () * 10000 ));
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Response command processing result ");
CdAnswer. countDown ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
};
Service.exe cute (runnable );
}
Try {
Thread. sleep (long) (Math. random () * 10000 ));

System. out. println ("Thread" + Thread. currentThread (). getName () +
"Coming soon ");
CdOrder. countDown ();
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Sent command, waiting for result ");
CdAnswer. await ();
System. out. println ("Thread" + Thread. currentThread (). getName () +
"All response results have been received ");
} Catch (Exception e ){
E. printStackTrace ();
}
Service. shutdown ();
}
}
In the above example, the main method represents the main thread, and three subthreads are created through the for loop. Two CountDownLatch objects are defined: cdOrder and cdAnswer. The cdOrder count is 1, which is used to control three subthreads, cdAnswer counts 3 to control the main thread. When the program starts to run, the main thread and sub-thread start to run simultaneously. Because the main thread needs to sleep for a period of time, the three sub-threads run, but encounter cdOrder. await (); must wait until the main thread cdOrder. countDown (); continue to run only when the count is changed to 0. The main thread runs to cdAnswer. await (); waiting, only when all three sub-threads are cdAnswer. countDown (); the main thread can run only when the count is changed to 0. The program running result is as follows:
[Java]
Thread pool-1-thread-2 is preparing to accept the command
Thread pool-1-thread-3 is preparing to accept the command
Thread pool-1-thread-1 is preparing to accept the command
Thread main is about to release commands
The main thread has sent the command and is waiting for the result.
Thread pool-1-thread-3 commands accepted
Thread pool-1-thread-2 commands accepted
Thread pool-1-thread-1 commands accepted
Thread pool-1-thread-1 response command processing result
Thread pool-1-thread-3 response command processing result
Thread pool-1-thread-2 responds to the command processing result
Thread main has received all response results


 

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.