Phaser也能夠實現countdownLatch的功能

/**
 * 可用用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();
            }
        }
    }
}
相關文章
相關標籤/搜索