/**
* 可用用phaser模拟countDownLatch
* awaitAdvance方法:如果传入的参数和当前的phase相等,线程就阻塞住等待phase的值增加;否则就立即返回
*/
public class PhaserTest2 {
private static Random random = new Random(System.currentTimeMillis());
public static void main(String[] args) throws InterruptedException {
Phaser phaser = new Phaser(4);
for (int i = 1; i <= 4; i++) {
new AwaitAdvanceTask(i, phaser).start();
}
System.out.println("before: "+phaser.getPhase());
int result = phaser.awaitAdvance(phaser.getPhase());
System.out.println("after: "+phaser.getPhase());
System.out.println("i = "+result);
}
static class AwaitAdvanceTask extends Thread {
private int no;
private Phaser phaser;
AwaitAdvanceTask(int no, Phaser phaser) {
this.no = no;
this.phaser = phaser;
}
@Override
public void run() {
try {
Thread.sleep(random.nextInt(5000));
System.out.println(no + " has worked done");
phaser.arriveAndAwaitAdvance();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}