CountDownLatch thread blocking usage instance, countdownlatch thread

Source: Internet
Author: User

CountDownLatch thread blocking usage instance, countdownlatch thread

There is a common problem in writing multithreading: the main thread (main) starts several subthreads (tasks) to complete concurrent tasks, the main thread will continue to execute other tasks of main only after all the sub-threads are completed.

By default, other sub-threads will not stop when the main thread exits. To terminate other sub-threads when the main thread exits, use subThread. setDaemon (true) to set the sub-thread to "daemon ".

If you want to execute other operations (such as result merging) after the main thread waits for all sub-threads to complete ). you can use the join () method to continue execution after all sub-threads are completed. As follows:

Example 1: Join implementation

Public class TestRunnable implements Runnable {/** thread name */private String threadName; public TestRunnable (String threadName) {this. threadName = threadName;} @ Override public void run () {System. out. println ("[" + threadName + "] Running! ");} Public static void main (String [] args) throws InterruptedException {List <Thread> lists = new ArrayList <Thread> (); for (int I = 0; I <5; I ++) {Thread thread = new Thread (new TestRunnable ("sub-Thread" + (I + 100); lists. add (thread); thread. start ();} System. out. println ("main Thread blocking, waiting for all sub-threads to complete execution"); for (thread: lists) {// If Thread is commented out. join (). After the startup, the main thread works concurrently with all the sub-threads, and does not wait until the sub-threads are completed before executing the thread. join ();} System. out. println ("All threads have been executed! ");}}

In addition, you can use the java. util. concurrent. CountDownLatch class to implement this scenario more concisely.

CountDownLatch is similar to Thread. join (). It can be used for collaboration between a group of threads and another group of threads.

For example, the main thread requires a series of preparations before doing a job. Only when these preparations are completed can the main thread continue its work. These preparations are independent of each other, therefore, it can be executed concurrently to increase the speed. In this scenario, CountDownLatch can be used to coordinate scheduling between threads.

When a Thread is directly created (before Java 5.0), we can use the Thread. join (). after JUC appears, because the threads in the thread pool cannot be directly referenced, CountDownLatch must be used.

CountDownLatch enables a group of threads and other threads to run completely before continuing. The CountDownLatch. await () method will block the current thread before the inverted count is 0.

Example 2: CountDownLatch implementation

Public class TestRunnable implements Runnable {/** handle main thread blocking (wait for all sub-threads) */private CountDownLatch countDown;/** thread name */private String threadName; public TestRunnable (CountDownLatch countDownLatch, String threadName) {this. countDown = countDownLatch; this. threadName = threadName;} @ Override public void run () {System. out. println ("[" + threadName + "] Running! [CountDownLatch. getCount () = "+ countDown. getCount () + "]. "); // after each independent sub-thread is executed, the countDownLatch value minus 1 countDown. countDown ();} public static void main (String [] args) throws InterruptedException {int countNum = 5; CountDownLatch countDownLatch = new CountDownLatch (countNum); for (int I = 0; I <countNum; I ++) {new Thread (new TestRunnable (countDownLatch, "subthread" + (I + 100 ))). start ();} System. out. println ("main thread Blocking, Waiting for all sub-threads to complete execution "); // endLatch. await () blocks the winner thread (main) until endLatch. countDownLatch is executed only when countDown () is zero. await (); System. out. println ("All threads have been executed! ");}}

Execution result:

For countDownLatch, note that the CountDownLatch. await () method will block the current thread before the inverted count is 0.
A) When await () is not applicable:

The execution result is as follows:

At this point, we can see that the main thread and sub-thread are concurrently executed. After the main thread is executed, the sub-thread is still executing, and the scenario we need is not implemented.

B) CountDownLatch. await () method when the inverted count is not 0

Execution result:

As you can see, the sub-thread execution is complete, but the countDownLatch's countdown value is not 0. It enters the continuous waiting state and does not wake up the main thread for execution. so countDownLatch. when await () takes effect, the Count value must be 0.

 

For more information, see [http://www.cnblogs.com/dennisit/p/4340611.html].

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.