简体   繁体   中英

Does CyclicBarrier reset itself for the last await?

I'm leaning about the CyclicBarrier and I wrote this demo.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import static java.util.concurrent.ThreadLocalRandom.current;
public class CyclicBarrierDemo {
    public static void main(final String[] args) {
        final int threads = 100;
        final CyclicBarrier barrier
            = new CyclicBarrier(threads, () -> System.out.println("tripped"));
        final int rounds = 5;
        for (int i = 0; i < threads; i++) {
            new Thread(() -> {
                    for (int j = 0; j < rounds; j++) {
                        try {
                            Thread.sleep(current().nextLong(1000L));
                            barrier.await();
                        } catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace(System.err);
                            return;
                        }
                    }
            }).start();
        }
    }
}

The program prints five tripped and quits, as I expected .

tripped
tripped
tripped
tripped
tripped

My question is that the CyclicBarrier instance reset itself when the last await() arrived? So that the output is expected? I couldn't find any words for that.

Think of CyclicBarrier as a gate and threads as cars.

The gate (barrier) will not open until it sees 100 cars waiting in front of it. When it opens, it will only allow that batch of 100 cars to pass through and close again. Same thing will happen again (cyclic) .

My question is that the CyclicBarrier instance reset itself when the last await() arrived?

Yes. In the sense that that instance can then be reused without the application needing to do something.

So that the output is expected?

Yes

I couldn't find any words for that.

The Javadoc says: "The barrier is called cyclic because it can be re-used after the waiting threads are released."

Also, the example shown in the javadoc would only work as described if the instance reset itself. Note that there are no explicit calls to reset() . (Furthermore, it is not clear that explictly calling reset() is useful if you want to reuse a barrier .... according to the method's javadoc.)

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