/**
The Countdownlatch class is a synchronous counter that is constructed with an int parameter, which is the initial value of the counter, each time the countdown () method is called, the counter is minus 1, the counter is greater than 0 o'clock, and the await () method blocks the program from continuing.
Countdownlatch, as it is written, is an inverted-count latch that triggers a specific event when the count is reduced to 0 o'clock. This feature allows the main thread to wait for the end of a child thread. This is illustrated by an example of a simulated athlete's race.
*/
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.Executor;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
public class Countdownlatchdemo {
private static final int player_amount = 5;
Public Countdownlatchdemo () {
TODO auto-generated Constructor stub
}
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
For each athlete, Countdownlatch minus 1 to end the game.
Countdownlatch begin = New Countdownlatch (1);
For the whole game, all the athletes are finished.
Countdownlatch end = new Countdownlatch (player_amount);
Player[] plays = new Player[player_amount];
for (int i=0;i<player_amount;i++)
Plays[i] = new Player (i+1,begin,end);
Set a specific thread pool with a size of 5
Executorservice exe = Executors.newfixedthreadpool (player_amount);
for (Player p:plays)
Exe.execute (P); assigning threads
System.out.println ("Race begins!");
Begin.countdown ();
try{
End.await (); Wait until the end state becomes 0, which is the end of the game
}catch (Interruptedexception e) {
Todo:handle exception
E.printstacktrace ();
}finally{
System.out.println ("Race ends!");
}
Exe.shutdown ();
}
}
Next is the Player class
import Java.util.concurrent.CountDownLatch;
Public class Player implements Runnable {
private int id;
Private Countdownlatch begin;
Private Countdownlatch end;
Public Player (int i, countdownlatch begin, Countdownlatch end) {
//TODO Auto-generated constructor s Tub
Super ();
This.id = i;
This.begin = begin;
This.end = end;
}
@Override
public void Run () {
//TODO auto-generated method stub
T ry{
Begin.await (); The status of the wait begin is 0
Thread.Sleep ((Long) (Math.random () *100)); Randomly allocated time, that is, athlete completion time
System.out.println ("Play" +id+ "arrived.");
}catch (interruptedexception e) {
//Todo:handle exception
E.printstacktrace ();
}finally{
End.countdown (); Reduce end state to 1 and end to 0
}
}
}
Analysis of Countdownlatch usage in Java