多个线程交替打印ABC package 多个线程交替打印ABC;import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier;/*** Created with IntelliJ IDEA.** @Author: AlenXu* @Date: 2024/03/20/10:10* @Description:*/ public class ThreadLoopPrint {// 共享计数器private static int sharedCounter = 0;public static void main(String[] args) {// 打印内容String printStr = "ABC";// 定义循环栅栏CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> System.out.println());// 执行任务Runnable runnable = new Runnable() {@Overridepublic void run() {for (int i = 0; i < printStr.length(); i++) {synchronized (this) {sharedCounter = sharedCounter > 2 ? 0 : sharedCounter; // 循环打印System.out.print(printStr.toCharArray()[sharedCounter++]);}try {// 等待3个线程都打印过一遍,继续下一轮cyclicBarrier.await();} catch (InterruptedException e) {e.printStackTrace();} catch (BrokenBarrierException e) {e.printStackTrace();}}}};// 开启多个线程new Thread(runnable).start();new Thread(runnable).start();new Thread(runnable).start();} }