Phaser使用

Phaser是jdk1.7引入的同步工具类,与countdownlatch和cyclicbarrier 功能重叠,但是又覆盖他们的功能。

package com.alibaba.dubbo.common.test;

import java.util.concurrent.*;

/**
 * @author liupengr
 * @date 2021/2/17 18:27
 */
public class PhaserMain {

    public static void main(String[] args) {
        ThreadPoolExecutor executor=new ThreadPoolExecutor(5,5,1, TimeUnit.SECONDS
                ,new ArrayBlockingQueue<Runnable>(10)){
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
            }
        };
        Phaser phaser=new Phaser(3);
        executor.submit(new PhaserDemo(phaser));
        executor.submit(new PhaserDemo(phaser));
        executor.submit(new PhaserDemo(phaser));
        //阻塞主线程,待子线程执行完毕,唤醒主线程
        phaser.awaitAdvance(0);
        System.out.println("====主线程执行完毕");
        executor.shutdown();
    }
}
package com.alibaba.dubbo.common.test;

import java.util.concurrent.Phaser;

/**
 * @author liupengr
 * @date 2021/2/17 18:28
 */
public class PhaserDemo implements Runnable {

    private final Phaser phaser;

    public PhaserDemo(Phaser phaser) {
        this.phaser = phaser;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"进来了");
            Thread.sleep(5000);
            //等待多个子线程到达公共屏障点
            phaser.arriveAndAwaitAdvance();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

上述例子中子线程使用 phaser.arriveAndAwaitAdvance();  进行子线程的阻塞

主线程中使用 phaser.awaitAdvance(0); 进行主线程租的。

输出结果:

Don’t hurry say have no choice, perhaps, next intersection will meet hope.
原文地址:https://www.cnblogs.com/volare/p/14409428.html