一个用Phaser控制多线程协作的小例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个用Phaser控制多线程协作的小例子相关的知识,希望对你有一定的参考价值。

package com.zl1030.Phaser;

import java.util.concurrent.Phaser;

public class Bot implements Runnable {
    private Phaser phaser;
    private int id;

    public Bot(int id, Phaser phaser) {
        super();
        this.id = id;
        this.phaser = phaser;
    }

    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("id:" + id + " wait...");
                Thread.sleep((long) (Math.random() * 5000));
                System.out.println("id:" + id + " arrive phase: " + phaser.getPhase());
                phaser.arriveAndAwaitAdvance();
                System.out.println("id:" + id + " after wait");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package com.zl1030.Phaser;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

public class Test {
    public static void main(String... args) throws Exception {
        Phaser phaser = new Phaser() {

            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("=====================phase:" + phase + " arrived!============================");
                return false;
            }

        };

        int botNum = 3;

        phaser.bulkRegister(botNum + 1);

        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < botNum; i++) {
            executorService.execute(new Bot(i + 1, phaser));
        }

        Scanner s = new Scanner(System.in);
        System.out.println("请输入字符串:");
        while (true) {
            String line = s.nextLine();

            if (line.equals("exit")) {
                System.out.println("Bye!");
                System.exit(0);
            } else {
                switch (line) {
                case "add":
                    phaser.bulkRegister(1);
                    botNum += 1;
                    executorService.execute(new Bot(botNum, phaser));
                    break;
                case "state":
                    System.out.println("phase: " + phaser.getPhase() + " arrivedParties:" + phaser.getArrivedParties()
                            + "/" + botNum);
                    break;
                case "continue":
                    phaser.arriveAndAwaitAdvance();
                    break;
                }
                System.out.println(">>>" + line);
            }
        }

    }

}


本文出自 “zl1030的记录” 博客,请务必保留此出处http://zl1030.blog.51cto.com/274507/1853846

以上是关于一个用Phaser控制多线程协作的小例子的主要内容,如果未能解决你的问题,请参考以下文章

并发编程系列之Phaser用法简介

并发编程系列之Phaser用法简介

多线程协作打印ABC之ReentrantLock版本

JDK并发工具之多线程团队协作:同步控制

Java 多线程 :入门- 线程间协作:挂起当前线程(wait)与通知其他线程继续执行(notify notifyAll)

用ucontext实现简单的用户空间协作多线程(转)