Skip to content

Instantly share code, notes, and snippets.

@Waterfox83
Created February 9, 2021 09:21
Example of using CyclicBarrier in Java
package concurrency;
import java.util.concurrent.*;
public class CyclicBarrierExample {
public static void main(String[] args) {
//Define a barrier initialized with 3.
CyclicBarrier barrier = new CyclicBarrier(3);
//Create a new thread pool with 3 threads.
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
//Execute the runnable code using thread.
executorService.submit(new CyclicBarrierTask(barrier, "Thread_" + i));
//Introduce some delay between each thread call.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executorService.shutdown();
System.out.println("All threads are done");
}
}
class CyclicBarrierTask extends Thread {
CyclicBarrier barrier;
String threadName;
public CyclicBarrierTask(CyclicBarrier barrier, String threadName) {
this.barrier = barrier;
this.threadName = threadName;
}
public void run() {
System.out.println(threadName + " executing long running process");
System.out.println("No. of threads already waiting at barrier: " + barrier.getNumberWaiting());
while (true) {
try {
//Each thread gets blocked here till all the threads reach this point
barrier.await();
System.out.println(threadName + " doing post barrier work");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
/*
Output:
Thread_0 executing long running process
No. of threads waiting at barrier: 0
Thread_1 executing long running process
No. of threads waiting at barrier: 1
Thread_2 executing long running process
No. of threads waiting at barrier: 2
Waiting for threads to finish
All threads are done
Thread_0 doing post barrier work
Thread_1 doing post barrier work
Thread_2 doing post barrier work
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment