Java Concurrency Tool Class (i) Countdownlatch waiting for multithreading to complete

Source: Internet
Author: User

function

Countdownlatch is a synchronization tool class that allows one or more threads to wait until the operation of another thread finishes executing

Introduction

Countdownlatch is introduced in java1.5, which exists under the Java.util.concurrent package, which allows 1 or more threads to wait until a set of operations is completed. It initializes an integer value that is the number of operands that the thread will wait. When a thread waits for the action to be performed, it uses the await () method. This method allows the thread to hibernate until the operation is complete. When an operation ends, it uses the countdown () method to reduce the internal counter of the Countdownlatch class. When the counter arrives 0 o'clock, this class wakes up all the threads that use the await () method to hibernate.

Application Scenarios

If there is such a demand, when we need to parse a multiple sheet data in Excel, we can consider using multi-threading, each thread resolves a sheet data, until all the sheet are resolved, the program needs to prompt parsing complete. In this requirement, the simplest way to implement the main thread to wait for all threads to complete sheet parsing operations is to use join. The code is as follows:

1  Public classJoincountdownlatchtest {2 3      Public Static voidMain (string[] args)throwsinterruptedexception {4Thread Parser1 =NewThread (NewRunnable () {5 @Override6              Public voidrun () {7             }8         });9 TenThread Parser2 =NewThread (NewRunnable () { One @Override A              Public voidrun () { -System.out.println ("Parser2 Finish"); -             } the         }); -  - Parser1.start (); - Parser2.start (); + Parser1.join (); - Parser2.join (); +System.out.println ("All parser finish"); A     } at  -}

Join is used to let the current thread of execution wait for the join thread to finish. The principle is to keep checking that the join thread is alive, and if the join thread survives, the current thread waits forever, and the code snippet is as follows, and wait (0) means wait forever.

while (IsAlive ()) {wait (0);}

  

Until the join thread aborts, the thread's this.notifyall will be called, the call Notifyall is implemented in the JVM, so the JDK does not see, interested classmates can look at the JVM source code. JDK does not recommend using the Wait,notify and Notifyall methods on thread instances.

The countdownlatch provided in the concurrency package after JDK1.5 can also implement this function of join, and is more powerful than join.

1  Public classCountdownlatchtest {2 3     StaticCountdownlatch C =NewCountdownlatch (2);4 5      Public Static voidMain (string[] args)throwsinterruptedexception {6         NewThread (NewRunnable () {7 @Override8              Public voidrun () {9SYSTEM.OUT.PRINTLN (1);Ten C.countdown (); OneSYSTEM.OUT.PRINTLN (2); A C.countdown (); -             } - }). Start (); the  - c.await (); -System.out.println ("3"); -     } +  -}

The Countdownlatch constructor takes a parameter of type int as a counter, and if you want to wait for n points to complete, this will pass in N.

When we call the countdown method of the Countdownlatch, N will subtract 1,countdownlatch the await will block the current thread until n becomes 0. Since the countdown method can be used anywhere, the N-points that are said here can be n threads, or the n execution steps of a 1-line thread. When using multiple threads, you only need to pass the Countdownlatch reference to the thread.

Other methods

If there is a parsing sheet thread processing is slow, we cannot let the main thread wait, so we can use another await method with the specified time, await (long time, timeunit unit): This method waits for a certain period, The current thread is no longer blocked. Join also has a similar approach.

Note: The counter must be greater than or equal to 0, just equal to 0, the counter is 0, and the await method is called without blocking the current thread. Countdownlatch It is not possible to reinitialize or modify the value of the internal counter of the Countdownlatch object. One thread calls the countdown method Happen-before another thread calls the await method.

Reference: The Art of Java concurrent programming

Java Concurrency Tool Class (i) Countdownlatch waiting for multithreading to complete

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.