Fundamentals 5 min read

Using CyclicBarrier for Alternating Thread Printing of ABC in Java

This article explains how to use Java's CyclicBarrier to coordinate three threads that alternately print the characters A, B, and C, providing a detailed analysis, example analogy, complete implementation code, execution result, and a brief summary of its relevance in multithreading interviews.

IT Services Circle
IT Services Circle
IT Services Circle
Using CyclicBarrier for Alternating Thread Printing of ABC in Java

The problem presented is to have three threads alternately print the characters "A", "B", and "C" in sequence, a common interview question for assessing Java multithreading knowledge.

Analysis : Among various solutions, the author prefers using JUC's CyclicBarrier because it naturally supports repeated synchronization points across multiple threads. The barrier makes a group of threads wait until all have reached a common point before proceeding, and it can be reused for subsequent cycles.

An analogy is given: a shuttle bus waits until it is full before departing, similar to how a CyclicBarrier waits for all participating threads before allowing them to continue to the next round.

Implementation Code :

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 3 threads alternately print ABC
 */
public class ThreadLoopPrint {
    // shared counter
    private static int sharedCounter = 0;
    public static void main(String[] args) {
        String printString = "ABC";
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
            // optional barrier action
        });
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < printString.length(); i++) {
                    synchronized (this) {
                        sharedCounter = sharedCounter > 2 ? 0 : sharedCounter; // cycle
                        System.out.println(printString.toCharArray()[sharedCounter++]);
                    }
                    try {
                        // wait for all 3 threads to finish one round
                        cyclicBarrier.await();
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}

The program's output shows the characters A, B, C printed in order repeatedly by the three threads, confirming the correct synchronization.

Conclusion : Implementing a cyclic multithreaded print task demonstrates a candidate's grasp of Java concurrency primitives; the time taken and code quality provide interviewers with a clear view of the applicant's fundamental coding skills.

Author Introduction : Wang Lei ("Lei Ge") has 13 years of frontline development experience, 3 years of teaching, and has held senior positions at companies like 360. He is a prolific technical blogger with millions of reads and multiple author recognitions.

JavaconcurrencymultithreadingThread SynchronizationCyclicBarrier
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.