Java CountDownLatch usage resolution
- 2020-05-30 20:07:33
- OfStack
The CountDownLatch class is a synchronous counter, which is constructed by passing in the int parameter, which is the initial value of the counter. Every time the countDown() method is called, the counter is reduced by 1. When the counter is greater than 0, the await() method will block the program to continue execution
CountDownLatch, as it is written, is a backcount latch that triggers specific events when the count is reduced to zero. With this feature, you can make the main thread wait for the end of the child thread. An example of a simulated athlete's competition is illustrated below.
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 every athlete, CountDownLatch Reduction of 1 Then the game is over
CountDownLatch begin = new CountDownLatch(1);
// For the entire competition, the competition is not over until all the athletes have 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);
// Sets the specific thread pool to size 5
ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for(Player p:plays)
exe.execute(p); // Allocate the thread
System.out.println("Race begins!");
begin.countDown();
try{
end.await(); // Waiting for the end State changes to 0 Is the end of the game
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("Race ends!");
}
exe.shutdown();
}
}
Next comes 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 stub
super();
this.id = i;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
begin.await(); // Waiting for the begin The status of 0
Thread.sleep((long)(Math.random()*100)); // Random allocation of time, that is, the athletes complete time
System.out.println("Play"+id+" arrived.");
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
end.countDown(); // make end State reduction 1 Eventually reduced to 0
}
}
}