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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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   51CTO博客,原文链接:http://blog.51cto.com/zl1030/1853846
上一篇:《可穿戴创意设计:技术与时尚的融合》一一1.4 新思路和新工具


下一篇:JS 创建长度为100的数组,数值为角标