CyclicBarrier 也叫同步屏障,可以让一组线程达到一个屏障时被阻塞,直到最后一个线程达到屏障时,所以被阻塞的线程才能执行。
(CyclicBarrier)好比一扇门,默认情况下关闭状态,堵住了线程执行道路,直到所有线程都就位,门才打开(同时执行await后面的代码),让所有线程一起通过。
CyclicBarrier相比于CountDownLatch可以多次使用
package CountDownLatchDemo;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Example {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(2);
new Thread(new A(cb)).start();
new Thread(new B(cb)).start();
}
}
class A implements Runnable {
private CyclicBarrier cb;
final static String B = "你";
final static String C = "我";
public A(CyclicBarrier cb) {
this.cb = cb;
}
@Override
public void run() {
try {
cb.await();//当调用run方法执行到此处会等待,直到达到CyclicBarrier(2)里面指定的最大数量后才开始同时执行后面的内容
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
synchronized (C) {
System.out.printf(C);
synchronized (B) {
System.out.printf(B);
}
}
}
}
class B implements Runnable {
private CyclicBarrier cb;
public B(CyclicBarrier cb) {
this.cb = cb;
}
@Override
public void run() {
try {
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
synchronized (A.B) {
System.out.printf(A.B);
synchronized (A.C) {
System.out.printf(A.C);
}
}
}
}
package CountDownLatchDemo;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class HorseRace implements Runnable{
private final int trackLen; //赛道长度
private CyclicBarrier cb;
public HorseRace(int trackLen, CyclicBarrier cb) {
this.trackLen = trackLen;
this.cb = cb;
}
@Override
public void run() {
printMsg("准备就绪");
try {
cb.await();
System.out.printf("出发了");
for (int i =0; i< trackLen; i++) {
Thread.sleep(new Random().nextInt(200));
}
printMsg("跑完了");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
private void printMsg(String msg) {
System.out.printf(getNowTime() + " " + Thread.currentThread().getName() + "-" + msg);
}
private String getNowTime() {
LocalTime now = LocalTime.now();
String formattedTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss:SSS"));
return formattedTime;
}
}
package CountDownLatchDemo;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
public class HorseRaceGame {
public static void main(String[] args) throws InterruptedException {
int tractLen = 10, horseRaceCount = 5;
CyclicBarrier cb = new CyclicBarrier(horseRaceCount);
for (int i = 0; i < horseRaceCount; i++) {
Thread thread = new Thread(new HorseRace(tractLen,cb));
Thread.sleep(new Random().nextInt(50));
thread.start();
}
}
}