@Test
public void test03() throws Exception{
CyclicBarrier cb = new CyclicBarrier(2); //new栅栏,并作为构造方法传入
new Thread(new Horse1(cb)).start();
new Thread(new Horse2(cb)).start();
Thread.sleep(2000); //防止主线程提前结束掉
}
class Horse1 implements Runnable{
CyclicBarrier cb;
public Horse1(CyclicBarrier cb) {
this.cb = cb;
}
@Override
public void run() {
try {
System.out.println("horse1 arrive the barrier");
cb.await(); //等待-1
System.out.println("horse1 running");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Horse2 implements Runnable{
CyclicBarrier cb;
public Horse2(CyclicBarrier cb) {
this.cb = cb;
}
@Override
public void run() {
System.out.println("horse2 not ready");
try {
Thread.sleep(1000);
System.out.println("horse2 arrive the barrier");
cb.await(); //等待-1 等等待的数量满2之后,放行
System.out.println("horse2 running");
} catch (Exception e) {
e.printStackTrace();
}
}
}
horse1 arrive the barrier
horse2 not ready
horse2 arrive the barrier
horse2 running
horse1 running