Understanding Java CyclicBarrier with Practical Examples
This article explains Java's CyclicBarrier synchronization tool, compares it with CountDownLatch, demonstrates basic and array‑sum examples with reusable barriers and callback actions, and shows how it can coordinate multiple threads for tasks such as parallel computation and result aggregation.
CyclicBarrier is a Java synchronization utility that makes multiple threads wait at a barrier until all have arrived, then releases them to continue; unlike CountDownLatch it can be reused and supports a callback task.
Below is a simple demonstration where a CyclicBarrier is created for three threads, each printing messages before and after reaching the barrier, and a callback prints a message when all threads have arrived:
package com.sample.interview.multithread;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
int n = 3;
CyclicBarrier barrier = new CyclicBarrier(n, new Runnable() {
public void run() {
System.out.println("执行回调,所以线程都已经达到屏障");
}
});
Thread t1 = new Thread(new ThreadDemo(barrier, "任务1"));
Thread t2 = new Thread(new ThreadDemo(barrier, "任务2"));
Thread t3 = new Thread(new ThreadDemo(barrier, "任务3"));
t1.start();
t2.start();
t3.start();
}
static class ThreadDemo implements Runnable {
private final CyclicBarrier barrier;
private final String name;
public ThreadDemo(CyclicBarrier barrier, String name) {
this.barrier = barrier;
this.name = name;
}
public void run() {
try {
System.out.println(name + "达到屏障之前");
// 等待其他线程
barrier.await();
System.out.println(name + "线程通过屏障");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}The program prints each thread's message before the barrier, then the callback message, followed by each thread's message after passing the barrier, demonstrating that the barrier synchronizes the threads and executes the callback once all have arrived.
CyclicBarrier is a powerful tool for scenarios where several threads perform independent work and later need to combine results, such as data aggregation or parallel chunk processing.
A more realistic example shows how to compute the sum of an array using multiple threads that each sum a portion of the array and then combine their partial sums at a barrier:
package com.sample.interview.multithread;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierSum {
private static final int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private static final int THREAD_COUNT = 3; // 多线程数量
private static int[] partialSums; // 存储每个线程的部分和
private static volatile int totalSum = 0; // 最终总和
public static void main(String[] args) {
partialSums = new int[THREAD_COUNT];
CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () -> {
// 当所有线程到达屏障时,汇总部分和
for (int sum : partialSums) {
totalSum += sum;
}
System.out.println("数组总和为: " + totalSum);
});
int chunkSize = arr.length / THREAD_COUNT;
for (int i = 0; i < THREAD_COUNT; i++) {
int start = i * chunkSize;
int end = (i == THREAD_COUNT - 1) ? arr.length : start + chunkSize;
new Thread(new Worker(i, start, end, barrier)).start();
}
}
static class Worker implements Runnable {
private final int id; // 线程编号
private final int start; // 数组起始索引
private final int end; // 数组结束索引(不包含)
private final CyclicBarrier barrier;
public Worker(int id, int start, int end, CyclicBarrier barrier) {
this.id = id;
this.start = start;
this.end = end;
this.barrier = barrier;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i < end; i++) {
sum += arr[i];
}
partialSums[id] = sum; // 存储部分和
try {
barrier.await(); // 等待其他线程
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}When all three worker threads finish computing their partial sums, the barrier’s callback aggregates them and prints the total array sum, illustrating how CyclicBarrier can coordinate parallel computation and result merging.
Follow the author’s WeChat ("互联网全栈架构") for more programming tips, and feel free to like, comment, or ask questions.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.