Phaser 介绍及应用详解

  Phaser是JDK提供的同步辅助类,用来解决多线程间分阶段同步完成任务的工具类。其和CountDownLatch、CyclicBarrier功能类似,但Phaser提供了更加丰富的功能,使用上更加灵活。

  演示示例:

package com.securitit.serialize.juc;

import java.util.Date;
import java.util.concurrent.Phaser;

import org.assertj.core.util.DateUtil;

public class PhaserTester {
	
	private static final Phaser phaser = new Phaser(3);
	
	public static void main(String[] args) throws Exception {
		new Thread(() -> {
			try {
				Thread.sleep(5000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点A.");
				Thread.sleep(1000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点B.");
			} catch (Exception ex) {
				ex.printStackTrace();
			} 
		}).start();
		new Thread(() -> {
			try {
				Thread.sleep(2000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点A.");
				Thread.sleep(2000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点B.");
			} catch (Exception ex) {
				ex.printStackTrace();
			} 
		}).start();
		new Thread(() -> {
			try {
				Thread.sleep(1000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点A.");
				Thread.sleep(5000);
				phaser.arriveAndAwaitAdvance();
				System.out.println(
						DateUtil.formatAsDatetime(new Date()) + " " + Thread.currentThread().getName() + " 线程集合点B.");
			} catch (Exception ex) {
				ex.printStackTrace();
			} 
		}).start();
	}

}

  输出结果:

2020-06-27T15:16:52 Thread-0 线程集合点A.
2020-06-27T15:16:52 Thread-1 线程集合点A.
2020-06-27T15:16:52 Thread-2 线程集合点A.
2020-06-27T15:16:57 Thread-2 线程集合点B.
2020-06-27T15:16:57 Thread-0 线程集合点B.
2020-06-27T15:16:57 Thread-1 线程集合点B.

  从结果可以看出,arriveAndAwaitAdvance可以实现线程协作,完成线程集合等功能。

你可能感兴趣的:(#,JUC,并发工具集)