JUC之Phaser的使用

Phaser是并发包juc.concurrent包下的一个关于线程同步和线程通信的一个工具类,类似于CountDownLanchCyclicBarrier,不同的是
Phaser可以用来根据步骤,等待线程按步骤同时触发执行。

package com.example.test;

import com.example.abstractClass.B;

import java.util.concurrent.Phaser;

public class A extends B {
    void a2() {
        super.a();
    }

    public static void main(String[] args) {
        // Phaser 参数为:维护线程个数
        Phaser phaser = new Phaser(10) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("phase: " + phase+ " registeredParties: " + registeredParties);
                return phase == 10;
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new C(phaser), "Thread" + i);
            thread.start();
        }
    }
}


class C implements Runnable {

    private Phaser phaser;

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

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " do something 1 ");
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + " do something 2 ");
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + " do something 3 ");
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + " do something 4 ");
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + " do something 5 ");
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + " do something 6 ");
        phaser.arriveAndAwaitAdvance();
    }
}

打印查看:
JUC之Phaser的使用_第1张图片

Phaser的 onAdvance(int phase, int registeredParties) 方法phase指的是 phaser.arriveAndAwaitAdvance() 方法执行的次数,在创建Phaser的构造参数中,入参指的是参与维护线程的数量;

你可能感兴趣的:(Java,java)