This article was transferred from:http://www.itzhai.com/the-introduction-and-use-of-a-countdownlatch.html
Countdownlatch
1, Class Introduction
A synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed. Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately. This behavior occurs only once-the count cannot be reset. One thread (or more), waiting for another n thread to complete something before it can execute
2. Usage Scenarios
in some applications, you need to wait for a certain condition to meet the requirements before you can do the following, and when the thread is finished, the event is triggered for later action. You can use Countdownlatch at this time. Countdownlatch the most important method is countdown () and await (), the former is mainly a countdown, the latter is waiting for the countdown to 0, if not reached 0, only blocking wait. 3. Method Description Countdown
Countdown ()
-
Decrements the latch count and, if the count reaches 0, releases all waiting threads. If the current count is greater than 0, the count is reduced. If the new count is zero, all waiting threads are re-enabled for thread scheduling purposes.
If the current count equals zero, no action occurs.
Await
await (Long timeout, Timeunit unit) throws Interruptedexception
-
-
causes the current thread to wait until the latch is counted down to 0, unless the thread is interrupted or the specified wait time is exceeded. If the current count is zero, this method returns the
true value immediately.
If the current count is greater than 0, the current thread is disabled for thread scheduling purposes, and the thread will remain dormant until one of the following three situations occurs:
countDown()the count reaches 0 due to the calling method;
- One of the other threads interrupts the current thread, or
- The specified wait time has been exceeded.
If the count reaches 0, the method returns a true value.
If the current thread:
- The interrupt state of the thread has been set when entering this method;
- is interrupted while waiting,
is thrown InterruptedException , and the current thread's interrupted state is cleared. If the specified wait time is exceeded, the return value is false . If the time is less than or equal to zero, this method does not wait at all.
-
-
-
Parameters:
-
timeout -The maximum time to wait
-
unit -the
timeout time unit of the parameter.
-
Return:
-
Returns if the count reaches 0, or
true if the wait time is exceeded before the count reaches 0
false
-
Thrown:
-
InterruptedException -If the current thread is interrupted while waiting
4. Relevant examples
1 Public classCountdownlatchtest {2 3 //The 100-metre race was simulated and 10 players were ready to wait until the referee commanded. When everyone gets to the finish line, the game is over. 4 Public Static voidMain (string[] args)throwsinterruptedexception {5 6 //start of the countdown lock7 FinalCountdownlatch begin =NewCountdownlatch (1); 8 9 //end of the countdown lockTen FinalCountdownlatch end =NewCountdownlatch (10); One A //10 Contestants - FinalExecutorservice exec = Executors.newfixedthreadpool (10); - the for(intindex = 0; Index < 10; index++) { - Final intNO = index + 1; -Runnable Run =NewRunnable () { - Public voidrun () { + Try { - //if the current count is zero, this method returns immediately. + //wait A begin.await (); atThread.Sleep ((Long) (Math.random () * 10000)); -System.out.println ("No." + No + "arrived"); -}Catch(interruptedexception e) { -}finally { - //when each player reaches the end, end is reduced by one - End.countdown (); in } - } to }; + Exec.submit (run); - } theSystem.out.println ("Game Start"); * //Begin minus one and start playing $ Begin.countdown (); Panax Notoginseng //wait for end to become 0, that is, all players reach the end - end.await (); theSystem.out.println ("Game over"); + Exec.shutdown (); A } the}
5. Output results
Game Start
No.9 arrived
No.6 arrived
No.8 arrived
No.7 arrived
No.10 arrived
Arrived
No.5 arrived
No.4 arrived
No.2 arrived
No.3 arrived
Game over Data supplement, the following example is derived from thinking in Java (the above example is different from the above example is a task to wait until more than one task to complete, and thinking in Java is a bit more advanced, Multiple tasks wait until multiple tasks are completed to unlock): Code 1:
1 PackageCom.cakushin.thread.countdownlatch;2 3 ImportJava.util.Random;4 ImportJava.util.concurrent.CountDownLatch;5 6 Public classTaskportionImplementsRunnable {7 Private Static intCounter = 0;8 Private Final intid = counter++;9 Private StaticRandom Rand =NewRandom (47);Ten Private FinalCountdownlatch latch; One A Publictaskportion (Countdownlatch latch) { - This. Latch =latch; - } the - @Override - Public voidrun () { - Try { + doWork (); - Latch.countdown (); +}Catch(interruptedexception e) { A e.printstacktrace (); at } - } - - Private voidDoWork ()throwsinterruptedexception { -Thread.Sleep (Rand.nextint (2000)); -System.out.println ( This+ "completed!"); in } - to PublicString toString () { + returnString.Format ("%1$-3d", id); - } the *}
Code Listing 2:
1 PackageCom.cakushin.thread.countdownlatch;2 3 ImportJava.util.concurrent.CountDownLatch;4 5 Public classWaitingtaskImplementsRunnable {6 Private Static intCounter = 0;7 Private Final intid = counter++;8 Private FinalCountdownlatch latch;9 Ten Publicwaitingtask (Countdownlatch latch) { One This. Latch =latch; A } - - @Override the Public voidrun () { - Try { - latch.await (); -System.out.println ("Latch barrier passed for" + This); +}Catch(interruptedexception e) { -System.out.println ( This+ "Interrupted"); + } A } at - PublicString toString () { - returnString.Format ("Watingtask%1$-3d", id); - } - -}
Code Listing 3:
1 PackageCom.cakushin.thread.countdownlatch;2 3 ImportJava.util.concurrent.CountDownLatch;4 ImportJava.util.concurrent.ExecutorService;5 Importjava.util.concurrent.Executors;6 7 Public Final classCountdownlatchdemo {8 9 Static Final intSIZE = 100;Ten One /** A * @authorAdministrator - * @paramargs - */ the Public Static voidMain (string[] args) { -Executorservice exec =Executors.newcachedthreadpool (); -Countdownlatch latch =NewCountdownlatch (SIZE); - for(inti = 0; I < 10; i++){ +Exec.execute (Newwaitingtask (latch)); - } + for(inti = 0; I < 100; i++){ AExec.execute (Newtaskportion (latch)); at } -SYSTEM.OUT.PRINTLN ("launched All Tasks"); - Exec.shutdown (); - } - -}
Java concurrency, Countdownlatch use