简体   繁体   中英

Barrier Synchronization (Output, increment and wait)

I want to make synchronized threads wait for each other. In the example program, each thread simply counts up to 100. I want the threads to wait every 10 outputs.

Because I am preparing for an exam, I would like to use the CyclicBarrier method.

Here is the code:

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);
        }

    }

and the Main-Class

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();
        }
    }

How do I insert the barriers?

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
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM