0

我想让同步线程互相等待。在示例程序中,每个线程最多计数为 100。我希望线程每 10 个输出等待一次。

因为我正在准备考试,所以我想使用CyclicBarrier方法。

这是代码:

public class NumberRunner extends Thread {

    private int number;

    private CyclicBarrier barrier;

    public NumberRunner(int n, CyclicBarrier b) {
        number = n;
        barrier = b;
    }

    public void run() {

        for (int i = 0; i < 100; i++) {

            System.out.println("Thread " + number + ": " + i);
        }

    }

和主班

public class Barriers {

    private final static int NUMBER = 3;

    public static void main(String[] args) {

        CyclicBarrier barrier = new CyclicBarrier(3);

        NumberRunner[] runner = new NumberRunner[NUMBER];
        for (int i = 0; i < NUMBER; i++) {
            runner[i] = new NumberRunner(i, barrier);
        }
        for (int i = 0; i < NUMBER; i++) {
            runner[i].start();
        }
    }

如何插入障碍?

4

1 回答 1

1
for (int i = 0; i < 100; i++) {
    System.out.println("Thread " + number + ": " + i);
    if ((i + 1) % 10 == 0) {
        try {
            barrier.await();
        } catch () {}//whatever exceptions b.await() throws
    }   
}
于 2019-09-25T14:37:16.500 回答