Java Concurrency Tool Class-COUNTDOWNLATCH1, Introduction
Countdownlatch is the Java Concurrency Tool class introduced after Java1.5, placed under the Java.util.concurrent package http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html official API.
Countdownlatch enables one or more threads to wait for other threads to complete their work before execution ; Countdownlatch is an implementation of the 5+ inside the JDK.
latching (Latch): A synchronous method that delays the progress of a thread until the thread reaches an endpoint state. In layman's words, a latch is equivalent to a door, all threads are blocked before the door opens, and once the door opens all threads will pass, but once the door opens and all threads pass through, then the state of the lock fails, and the state of the door cannot be changed, only the state of the Open. This means that the latching state is a one-time, which ensures that all specific activities need to be completed before latching is opened.
The first interaction with Countdownlatch is that the main thread waits for other threads, and the main thread must call the await method immediately after the other thread is started, so that the main thread's operation will block on this method until other threads have completed their respective tasks.
the other n threads must refer to the Latching object , because they need to notify the Countdownlatch object that they have completed their respective tasks, and this mechanism is done through the countdown () method. Each time this method is called, the count value initialized in the constructor is reduced by 1, so when n threads call this method, the value of count is equal to 0, then the main thread can restore its own task through the await method.
The main thread here is a relative concept that needs to be analyzed based on the scene created by Countdownlatch.
2. Main methods
Unique methods: PublicCountdownlatch (intcount);//Specifies the number of counts, which can only be set 1 times Public voidCountdown ();//call this method to count minus 1 Public voidAwait ()throwsInterruptedexception//calling this method will block the current thread until the value of the timer is 0 unless the thread is interrupted. Public Long GetCount ();//get the current countPublicBooleanAwaitLongTimeout, timeunit unit)//calling this method will block the current thread until the value of the timer is 0, unless the thread is interrupted or the counter times out, and false indicates that the counter timed out. From Object inherited:Clone, Equals, Hashcode, notify, Notifyall, wait, and so on.
3. Usage Scenarios
(1) Open multiple threads to download a large file, each thread only download a fixed section, and finally the other thread splicing all segments.
(2) The main thread of the application wants to execute after all the framework services have been started by the threads responsible for starting the framework service.
(3) Ensure that a calculation is not performed until the required resources are initialized.
......
4. Reference example
(1) Turn from: http://www.iteye.com/topic/1002652
Public classCountdownlatchdemo {Final StaticSimpleDateFormat sdf=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Public Static voidMain (string[] args)throwsinterruptedexception {countdownlatch latch=NewCountdownlatch (2);//collaboration between two workersWorker worker1=NewWorker ("Zhang San", 5000, latch); Worker Worker2=NewWorker ("Li si", 8000, latch); Worker1.start ();//Worker2.start ();//Latch.await ();//wait for all the workers to finish the workSystem.out.println ("All work done at" +sdf.format (NewDate ())); } Static classWorkerextendsthread{String Workername; intWorktime; Countdownlatch latch; PublicWorker (String Workername,intworktime, Countdownlatch latch) { This. workername=Workername; This. worktime=Worktime; This. latch=latch; } Public voidrun () {System.out.println ("Worker" +workername+ "do-work-begin at" +sdf.format (NewDate ())); DoWork ();//work.System.out.println ("Worker" +workername+ "Do Work Complete at" +sdf.format (NewDate ())); Latch.countdown ();//The worker finishes the work and the counter is reduced by one } Private voiddoWork () {Try{thread.sleep (worktime); } Catch(interruptedexception e) {e.printstacktrace (); } } } } View Code
(2) Official website example (recommended implementation model 1): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
classDriver {// ... voidMain ()throwsinterruptedexception {countdownlatch startsignal=NewCountdownlatch (1); Countdownlatch donesignal=NewCountdownlatch (N); for(inti = 0; i < N; ++i)//Create and start threads NewThread (NewWorker (startsignal, donesignal)). Start (); Dosomethingelse (); //don ' t let run yetStartsignal.countdown ();//Let all threads proceedDosomethingelse (); Donesignal.await (); //wait for all to finish } } classWorkerImplementsRunnable {Private FinalCountdownlatch startsignal; Private FinalCountdownlatch donesignal; Worker (Countdownlatch startsignal, Countdownlatch donesignal) { This. startsignal =startsignal; This. donesignal =donesignal; } Public voidrun () {Try{startsignal.await (); DoWork (); Donesignal.countdown (); } Catch(Interruptedexception ex) {}//return; } voiddoWork () {...}}View Code
(3) Official website example (recommended implementation Model 2): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Note:
1. Latch.countdown (); It is recommended to put it in the finally statement.
2. The operation of this counter is atomic, while only one thread can operate the counter.
5. Common Face Test
It is easy to solve the following interview questions through the above introduction:
(1) Explain the Countdownlatch concept?
(2) What are the differences between Countdownlatch and Cyclicbarrier?
(3) Give some examples of countdownlatch use?
(4) The Main method in the Countdownlatch class?
6. References
When to use countdownlatch:http://www.importnew.com/15731.html
Official website api:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/countdownlatch.html
Example: http://www.iteye.com/topic/1002652
Java Concurrency Tool class-Countdownlatch