Phaser也可以实现countdownLatch的功能
阅读原文时间:2023年07月15日阅读:3

/**
* 可用用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();  
    for (int i = ; i <= ; 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());  
            System.out.println(no + " has worked done");  
            phaser.arriveAndAwaitAdvance();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
    }  
}  

}