Java同步器Phaser(阶段器)

类似于循环障栅CyclicBarrier,不过有一个可变的计数器(JavaSE7中引入)

一个小例子简单说明用法:

PS:自我感觉良好,觉得看完这个例子都该懂了…O(∩_∩)O


import java.util.Random;
import java.util.concurrent.*;

/**
 *
 * @date 2020/5/29 17:09
 * @author wei.heng
 */
public class PhaserTest {

	public static void main(String[] args) {

		class Working implements Runnable {
			private String name;
			private Phaser ph;
			private int period = 3;

			private Working(String name, Phaser ph) {
				this.name = name;
				this.ph = ph;
				// 每创建一个runnable,我们就注册一个party
				ph.register();
			}

			@Override
			public void run() {

				for (int i = 1; i <= period; i++) {
					System.out.println(name + ":我开始第" + i + "阶段的工作了");
					int workingTime = 0;
					try {
						workingTime = new Random().nextInt(10);
						TimeUnit.SECONDS.sleep(workingTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					ph.arriveAndAwaitAdvance();
					System.out.println(name + ":" + ph.getPhase() + "," + ph.getArrivedParties() + ","
						+ ph.getUnarrivedParties() + "," + ph.getRegisteredParties());
					System.out.println(name + ":我第" + i + "阶段的工作做完了, 耗时" + workingTime + "秒");
				}
				ph.arriveAndDeregister();
			}

		}

		// 创建一个线程池来管理所有的工作
		ExecutorService executorService = new ThreadPoolExecutor(5, 20
			, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(16)
			, r -> new Thread(r, "TestThread"));
		// 注册一个阶段器,初始化管理的线程数为3 - 如果这里初始化了,就不用在Working 的构造方法中进行register了
		// Phaser ph = new Phaser(3);
		// 注册一个阶段器
		Phaser ph = new Phaser();
		executorService.submit(new Working("thread-1", ph));
		executorService.submit(new Working("thread-2", ph));
		executorService.submit(new Working("thread-3", ph));
	}

}

输出结果:

thread-1:我开始第1阶段的工作了
thread-2:我开始第1阶段的工作了
thread-3:我开始第1阶段的工作了
thread-2:1,0,3,3
thread-1:1,0,3,3
thread-3:1,0,3,3
thread-1:我第1阶段的工作做完了, 耗时0秒
thread-2:我第1阶段的工作做完了, 耗时1秒
thread-1:我开始第2阶段的工作了
thread-3:我第1阶段的工作做完了, 耗时1秒
thread-2:我开始第2阶段的工作了
thread-3:我开始第2阶段的工作了
thread-3:2,0,3,3
thread-1:2,0,3,3
thread-2:2,0,3,3
thread-1:我第2阶段的工作做完了, 耗时4秒
thread-3:我第2阶段的工作做完了, 耗时9秒
thread-1:我开始第3阶段的工作了
thread-2:我第2阶段的工作做完了, 耗时8秒
thread-3:我开始第3阶段的工作了
thread-2:我开始第3阶段的工作了
thread-2:3,0,3,3
thread-1:3,0,3,3
thread-3:3,0,3,3
thread-1:我第3阶段的工作做完了, 耗时7秒
thread-2:我第3阶段的工作做完了, 耗时7秒
thread-3:我第3阶段的工作做完了, 耗时4秒

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值