import java.util.concurrent.CyclicBarrier;
/**
* CyclicBarrier示例,模拟一家3口,不同时间到家后,同时开餐。
* @author Administrator
*
*/
public class CyclicBarrierDemo {
public static void main(String[] args) {
Runnable eat=() ->{
String name=Thread.currentThread().getName();
System.out.println(name+" say,start eat!");//开吃
};
final CyclicBarrier cb=new CyclicBarrier(3,eat);
Runnable goHome=() -> {
int ra=(int) (Math.random()*200);
try {
Thread.sleep(ra);//模拟路上耗时
} catch (InterruptedException e) {
e.printStackTrace();
}
String name=Thread.currentThread().getName();
System.out.println(name+",goHome!");
try {
cb.await();//到家了
} catch (Exception e) {
e.printStackTrace();
}
};
Thread fa=new Thread(goHome,"fa");
Thread ma=new Thread(goHome,"ma");
Thread son=new Thread(goHome,"son");
son.start();
fa.start();
ma.start();
}
}
运行结果