Java multithreaded Programming Countdownlatch Synchronization tool use instance _java

Source: Internet
Author: User

Like the countdown counter, the countdown method of calling the Countdownlatch object will reduce the counter by 1, and when it arrives 0 o'clock, all the waiting people will start executing.

Java.util.concurrent.CountDownLatch
A synchronization helper class that allows one or more threads to wait all the time before completing a set of operations that are being performed in another thread. Initializes the countdownlatch with the given count. Because the countdown () method is invoked, the await method remains blocked until the current count reaches 0. After that, all waiting threads are freed and all subsequent calls to the await are returned immediately. This phenomenon occurs only once--the count cannot be reset. If you need to reset the count, consider using Cyclicbarrier.

Countdownlatch is a general-purpose synchronization tool that has many uses. The countdownlatch that is initialized with Count 1 is used as a simple open/Guan, or Portal: All threads calling await are waiting at the entrance until the entry is opened by a thread that calls Countdown (). Countdownlatch initialized with n can cause a thread to wait until N threads complete an operation, or to wait until an operation completes N.

A useful feature of Countdownlatch is that it does not require the thread that calls the countdown method to wait until the count arrives 0 o'clock, and until all threads pass, it simply blocks any thread from continuing through a await.

For example: Multiple athletes waiting for a referee to order: The referee and all the athletes after the release of the results

Package com.ljq.test.thread;
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;
 
Import java.util.concurrent.Executors; public class Countdownlatchtest {public static void main (string[] args) {Executorservice service = Executors.new
    Cachedthreadpool ();
    The referee issued the command counter, the counter is 0, the athlete runs final countdownlatch cdorder = new Countdownlatch (1); 
     
    The athlete ran to the end of the counter, announcing the result of the 0 referee final Countdownlatch cdanswer = new Countdownlatch (3); Generates 3 athletes for (int i=0;i<3;i++) {Runnable Runnable = new Runnable () {public void run () {TR            
            y {System.out.println ("thread" + thread.currentthread (). GetName () + "Preparing to accept command");
            Cdorder.await ();               
            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "accepted command"); 
            Thread.Sleep ((Long) (Math.random () *10000));           
         SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "respond to command processing results");   Cdanswer.countdown ();
          catch (Exception e) {e.printstacktrace ();
      }       
        }
      }; Service.execute (runnable);
     
      The athlete starts the task} try {//The referee rests a minute and then publishes the Command Thread.Sleep ((long) (Math.random () *10000));          
      SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "forthcoming command"); Cdorder.countdown (); 
      Command counter set to 0, publish command System.out.println ("thread" + thread.currentthread (). GetName () + "sent commands, waiting for results"); Cdanswer.await (); 
    Wait for all players, counter for 0 all sportsmen in place System.out.println ("thread" + thread.currentthread (). GetName () + "received all response results");
    catch (Exception e) {e.printstacktrace ();
 
  } service.shutdown ();

 }
}

return Result:

Thread pool-1-thread-3 is preparing to accept the command thread pool-1-thread-1 is preparing to accept the command thread
Pool-1-thread-2 is preparing to accept the command
thread main is about to release the command
Thread main has sent a command, waiting for the result thread Pool-1-thread-2 has accepted the command thread Pool-1-thread-1 has accepted the command thread
Pool-1-thread-3 has accepted the
command
Thread pool-1-thread-3 response command processing result thread
pool-1-thread-2 response command processing result
thread pool-1-thread-1 response 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.