The use of Countdownlatch and Cyclicbarrier in Java concurrent programming
In a multithreaded programming design, you often encounter a scenario where a thread waits for one or more threads, and how should this scenario be resolved?
If a thread waits for a thread, it can be implemented by await () and notify ().
If a thread waits for multiple threads, you can use Countdownlatch and cyclicbarrier to achieve better control.
Below is a detailed description of the following Countdownlatch scenarios:
For example: Hundred meters Race: 8 athletes run at the same time, due to speed, there will be a first to the end of the terminal and the end of the situation, and the end of a statistical performance of the instrument, when all the players arrive at the end, it will be counted all the results and sequencing, and then send the result to the system of reporting results.
In fact, this is a countdownlatch scenario: a thread or threads waiting for other threads to run their next work after they have reached a target, while waiting for "other threads" to reach this goal continues their tasks below.
In this scenario:
1. Waiting "Other threads"------>8 Athletes
2. Wait for "Other threads" of this thread------> end of the instrument of statistical achievement
So, how to use Countdownlatch to achieve the above scenario of threading control and scheduling it?
The Countdownlatch class in the JDK has a common construction method:countdownlatch (int count);
Two common methods: await () and Countdown ()
Where count is the initialization number in a counter, such as the number initialized is 2, when a line thread call Countdown (), then this counter is reduced by one, when the thread calls await (), the thread waits for this counter to become 0, when the counter becomes 0 o'clock, This thread continues to work on its own. Here is the implementation of the above Countdownlatch scenario:
work Class (athlete):
Import java.util.concurrent.countdownlatch;public class work implements runnable { private int id; private countdownlatch beginSignal; private CountDownLatch endSignal; Public work (int id, countdownlatch begin, countdownlatch end) { this.id = id; this.beginsignal = begin; this.endsignal = end; } @Override public void Run () { try { system.out.println ("Ready to finish ..." +ID); &nbsP;beginsignal.await (); System.out.println ("Starting ..." +id); System.out.println ("Work" + id + "reach Destination"); endsignal.countdown (); system.out.println ("Work" + id + "continue to do other things"); } catch (interruptedexception e) { // TODO Auto-generated catch block e.printstacktrace (); } } public static void main (String[] args) { countdownlatch begsignal = new countdownlatch (1); countdownlatch endsignal = new countdownlatch (8); for (int i = 0; i < 8; i+ +) { new thread (new Work (i, begsignal, endsignal)). Start (); } try { thread.currentthread (). Sleep ( ; } catch (interruptedexception e) { e.printstacktrace (); } system.out.println ("-------------------------------"); try { begsignal.countdown (); //Unified starting endsignal.await (); //waiting for athletes to reach the finish line SYSTEM.OUT.PRINTLN ("Results sent to reporting system"); } catch ( Interruptedexception e) { E.printstacktrace (); } }}
Output Result:
Ready to finish. 4
Ready to finish. 5
Ready to finish. 1
Ready to finish. 2
Ready to finish. 6
Ready to finish. 0
Ready to finish. 3
Ready to finish. 7
-------------------------------
Start... 4
Start... 2
Start... 6
Work6 reach the finish line
Start... 1
Work1 reach the finish line
Start... 5
Work5 reach the finish line
Work1 continue to do other things
Work6 continue to do other things
Start... 7
Work7 reach the finish line
Work7 continue to do other things
Start... 3
Work3 reach the finish line
Work3 continue to do other things
Start... 0
Work2 reach the finish line
Work2 continue to do other things
Work4 reach the finish line
Work4 continue to do other things
Work0 reach the finish line
Work0 continue to do other things
Work5 continue to do other things
Results sent to the system reporting results
Below is a detailed description of the application scenario for Cyclicbarrier:
There are four players playing games, the game has three levels, each level must be the arrival of all players to allow clearance.
In fact, in this scenario, if a player a first to the level 1, he must wait for all other players to reach the level 1 o'clock to pass, that is, the threads need to wait for each other, which is different from the Countdownlatch application scenario, The thread in the Countdownlatch is going to continue to do something else after the target is running, and the thread here waits for another thread to finish the work below.
The Cyclicbarrier class in the JDK has two common construction methods:
1. Cyclicbarrier (int parties)
The parties is also a counter, for example, the count in parties is 3 when initialized, so the thread that owns the Cyclicbarrier object wakes up when the parties count is 3 o'clock. Note: The count in parties here is at runtime when the cyclicbarrier:await () is called, the count is added 1, always added to the initial value
2. Cyclicbarrier (int parties, Runnable barrieraction)
The parties here is the same as the previous construction method, which needs to be explained by the second entry (Runnable barrieraction), which is an object of the class that implements the Runnable interface. This means that when the parties is added to the initial value, the contents of the barrieraction are set.
Here's how to implement the above scenario:
Player Class (Player Class)
Java.util.concurrent.brokenbarrierexceptionjava.util.concurrent.cyclicbarrierpublic class player implements Runnable{ private CyclicBarrier cyclicBarrier; private int id; public player (int id, Cyclicbarrier cyclicbarrier) { this.cyclicbarrier = cyclicBarrier; this.id = id; } @Override public void run () { try { system.out.println ("Player" + id + "playing first off ..."); cyclicbarrier.await (); sysTem.out.println ("Player" + id + "Enter second pass ..."); } catch (interruptedexception e) { e.printstacktrace (); } catch ( Brokenbarrierexception e) { E.printstacktrace (); } } public static void main (String[] args) { cyclicbarrier cyclicbarrier = new cyclicbarrier (4, new Runnable () { @Override public void run () { &nBsp; system.out.println ("All players enter the second pass!") "); } }); for (int i = 0; i < 4; i++) { New thread (New player (I, cyclicbarrier)). Start (); } }}
Output Result:
Player 1 is playing first off ...
Player 2 is playing first off ...
Player 3 is playing first off ...
Player 0 is playing first off ...
All players go to the second pass!
Player 0 enters second pass ...
Player 1 enters second pass ...
Player 2 enters second pass ...
Player 3 enters second pass ...
The use of Countdownlatch and Cyclicbarrier in Java concurrent programming