一个用Phaser控制多线程协作的小例子
2016-09-19 00:47
239 查看
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); } } } }
相关文章推荐
- c#中子线程控制进度条的一个简单例子(多线程问题)
- C++使用临界区(互斥体)来控制多线程访问同一个变量(经典例子)
- 多线程的一个例子
- Winform 的一个多线程绑定DataGrid数据源的例子
- c#中子线程控制进度条的一个简单例子
- 一个多线程例子
- 一个Biztalk,SPS,InfoPath协作的例子
- 控制界面是否可输入的一个例子
- C#中子线程控制进度条的一个简单例子
- C#中子线程控制进度条的一个简单例子
- java一个多线程的经典例子
- 多线程(6): Java Threads例子的一个问题
- c#中子线程控制进度条的一个简单例子
- C# 一个多线程操作控件的例子.#######
- c#中子线程控制进度条的一个简单例子 - jinjazz - CSDNBlog
- 一个java多线程的例子
- c#中子线程控制进度条的一个简单例子
- 多线程:一个理解wait()与notify()的例子
- c#中子线程控制进度条的一个简单例子
- 用一个例子来说明程序开发过程中的粒度和弹性控制