Week 81 — What is the purpose of the `CyclicBarrier` class and how can it be used?
Question of the Week #81
What is the purpose of the
CyclicBarrier
class and how can it be used?4 Replies
CyclicBarrier
class is used to make threads wait for each other. When multiple threads have some subtask to do, and output of these subtasks needed to be combined as a final output, then the CyclicBarrier
class is used.Submission from rakin235
CyclicBarier is a synchronizer, it means allowing the set of threads to wait each other to reach a common execution point. For example, we have lots of thread and these thread will have a numbers, and we need to show each thread in a logical sort of order, otherwise we could not able to understand which thread is coming first or last. And it will be barier to another thread in this way. We can also calledd a barrier for CyclicBarier class
Submission from mufa__
Barriers allow threads to await on it until a certain point where the barrier is opened and all threads waiting on it are released and can continue execution.
A
CyclicBarrier
opens as soon as a specified number of threads are waiting on it.
This should print thread N is waiting...
for N
with different N
s from 0 to (excluding) 10 before any thread N is continuing
is printed. Then, all thread N is continuing
messages are printed.
What makes CyclicBarrier
different from other barriers is that it can be reused by threads calling await()
again after it has been opened. In this case, it starts again and reopens when the specified number of threads are waiting on that barrier once more.