java CountDownLatch 同步计数器

时间:2023-02-09 16:18:59

1..CountDownLatch 类

CountDownLatch类是一个同步辅助类,  他是同步计数器, 

CountDownLatch latch = new CountDownLatch(100)     设定计数器的初始值100,

调用countDown() 则计数器减去1,直到计数器等于0之前本句都可以执行

latch.await(); 方法阻塞程序执行  , 直到CountDownLatch 为0,则继续执行本句后面的代码


代码如下:

package countDownLatchDemo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

private static final int PLAYER_AMOUNT = 5;

public CountDownLatchDemo() {
}

/**
* @param args
*/
public static void main(String[] args) {
// 对于每位运动员,CountDownLatch减1后即结束比赛
CountDownLatch begin = new CountDownLatch(1);
// 对于整个比赛,所有运动员结束后才算结束
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);

// 设置特定的线程池,大小为5
ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for (Player p : plays)
exe.execute(p); // 分配线程
System.out.println("Race begins!");
begin.countDown();
try {
end.await(); // 等待end状态变为0,即为比赛结束
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
System.out.println("Race ends!");
}
exe.shutdown();
}
}

package countDownLatchDemo;

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) {
super();
this.id = i;
this.begin = begin;
this.end = end;
}

@Override
public void run() {
try {
begin.await(); // 等待begin的状态为0
Thread.sleep((long) (Math.random() * 100)); // 随机分配时间,即运动员完成时间
System.out.println("Play" + id + " arrived.");
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
end.countDown(); // 使end状态减1,最终减至0
}
}
}

结果:

Race begins!
Play5 arrived.
Play2 arrived.
Play4 arrived.
Play3 arrived.
Play1 arrived.
Race ends!