Synchronous auxiliary class CountDownLatch usage and countdownlatch usage

Source: Internet
Author: User

Synchronous auxiliary class CountDownLatch usage and countdownlatch usage

CountDownLatch is a synchronization helper class, which is like a countDown counter. when an object is created, the initial value is set through the constructor. The await () method of the CountDownLatch object is called to keep the current thread in the waiting state and countDown () when the Count reaches 0, all the waiting threads start to execute. It provides the following common methods:

Public CountDownLatch (int count); // The constructor parameter specifies the count public void countDown (); // if the current thread calls this method, the count minus public void await () throws InterruptedException; // when this method is called, the current thread will be blocked until the timer value is 0.

The usage is as follows:

Package basic; import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class TestCountDown {private static final int PLAYER_AMOUNT = 5; public static void main (String [] args) {/* for each athlete, countDownLatch starts the competition after 1 minus */CountDownLatch begin = new CountDownLatch (1);/* all athletes end after the end of the competition */CountDownLatch end = new CountDownLatch (PLAYER_AMOUNT); Player [] players = new Player [PLAYER_AMOUNT]; for (int I = 0; I <PLAYER_AMOUNT; I ++) {players [I] = new Player (I + 1, begin, end);}/* set a specific thread pool, with a size of 5 */ExecutorService executorService = Executors. newFixedThreadPool (PLAYER_AMOUNT); for (Player player: players) {/* allocate thread */executorService.exe cute (player);} System. out. println ("Race begins! ");/* All players wait for the start of the game signal */begin. countDown (); try {/* Wait until the end state changes to 0, that is, the end of the game */end. await ();} catch (InterruptedException e) {e. printStackTrace ();} finally {System. out. println ("Race ends! ");} ExecutorService. shutdown () ;}} class Player implements Runnable {private final int id; private final CountDownLatch begin; private final CountDownLatch end; public Player (int id, CountDownLatch begin, CountDownLatch end) {super (); this. id = id; this. begin = begin; this. end = end ;}@ Override public void run () {try {/* Wait for the begin status to 0 */begin. await ();/* random allocation time, that is, the athlete's completion time */Thread. sleep (long) (Math. random () * 100); System. out. println ("Play" + id + "arrived. ");} catch (InterruptedException e) {e. printStackTrace ();} finally {/* reduce the end state by 1, and the athletes in the current thread finish the competition */end. countDown ();}}}

Begin the code. countDown () is the start of the game signal, five begin. the await () thread starts execution. After execution, the end is executed in the finally block. countDown (). When the counter is reduced to 0, the end in the main method is awakened. await (), the program goes down and prints the end of the competition.

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. if the current count is zero then this method returns immediately. if the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen: 1.The count reaches zero due to invocations of the countDown () method; or 2. some other thread interrupts the current thread.

If the current thread: has its interrupted status set on entry to this method; or is interrupted while waiting, then java. lang. interruptedException is thrown and the current thread's interrupted status is cleared. throws: java. lang. interruptedException if the current thread is interrupted while waiting public void await () throws InterruptedException {sync. acquireSharedInterruptibly (1 );}

The above is the JDK source code of the core method await!

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.