Phaser

Phaser是CountDownLatch和CyclicBarrier的升级版:

demo:

public class PhaserTest {
    public static void main(String[] args) {
        // 三个部分
        int parties = 3;
        // 四个阶段
        int phases = 4;
        // new Phaser对象并重写完成阶段后执行方法
        Phaser phaser = new Phaser(parties) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("===phase " + phase + " end===");
                return registeredParties == 0;
            }
        };

        //创建线程并启动
        for (int i = 0; i < parties; i++) {
            int threadId = i;
            Thread t = new Thread(()-> {
                for (int currentPhase = 0; currentPhase < phases; currentPhase++) {
                    if(currentPhase == 0) {
                        System.out.println(String.format("第一阶段操作,Thread %s, Phase %s", threadId, currentPhase));
                    }
                    if(currentPhase == 1) {
                        System.out.println(String.format("第二阶段操作,Thread %s, Phase %s", threadId, currentPhase));
                    }
                    if(currentPhase == 2) {
                        System.out.println(String.format("第三阶段操作,Thread %s, Phase %s", threadId, currentPhase));
                    }
                    if(currentPhase == 3) {
                        System.out.println(String.format("第四阶段操作,Thread %s, Phase %s", threadId, currentPhase));
                    }
                    phaser.arriveAndAwaitAdvance();
                }
            });
            t.start();
        }
    }
}

 

posted @ 2021-06-17 17:24  圣金巫灵  阅读(248)  评论(0编辑  收藏  举报