?三个线程交替打印 ABC ,使用 JUC 下的 CyclicBarrier(循环栅栏,也叫循环屏障)来实现,因为循环栅栏天生就是用来实现一轮一轮多线程任务的,它的核心实现思路如下图所示:
?CyclicBarrier 作用是让一组线程相互等待,当达到一个共同点时,所有之前等待的线程再继续执行,且 CyclicBarrier 功能可重复使用。
public class Test {
private static int location = 0;
public static void main(String[] args) {
String content = "ABC";
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < content.length(); i++) {
synchronized (this) {
location = location > 2 ? 0 : location;
System.out.println(Thread.currentThread().getName() + ":" + content.charAt(location++));
}
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
}
};
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}
}