Learn java thread communication with me 3:CyclicBarrier
1. Introduction
This post would demo how to do the thread communication by using CountDownLatch. If you want to know the wait-notify communication, you can refer to the previous article, if you want to learn how to communicate through the volatile keyword, you can refer to this article,if you want to learn how to use CountDownLatch, you can view this post
1. Environments
- Java 1.8
2.1 The CyclicBarrier introduction
As the javadoc says:
It’s a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.
The CyclicBarrier is very similar to the CountDownLatch, the difference is the CyclicBarrier can be reused and is controlled in every thread.
This picuture shows how the CyclicBarrier works:
As the picture shows:
- There are three threads in the barrier, they are waiting for each other
- Worker0 runs fast, and it’s waiting for the max time
- Worker1 runs slower than worker0, and is also waiting for some time
- Worker2 runs slowest, and after it reaches the barrier, all threads unlocked
- The barrier executes the “allTaskDone” thread when all threads unlocked
2.2 The classic CyclicBarrier example code
- Each worker sleep for some time and call barrier.await to wait for the others
- The worker3 is the slowest thread
- The CyclicBarrier has 3 threads and one action, the action just print ‘all workers done’
Run the code and we get this:
As you can see
- workers started and then waiting
- after worker3 done, then ‘all workers done’ action executed
- we print the arrive index of every worker, the zero means the last
3. Summary
The CyclicBarrier is more flexible than CountDownLatch.
You can find the whole code examples on github project, the class source code is located at this, they are named like ThreadComm4_*.java
You can find detail documents about the java stream here: