CyclicBarrier是一个线程辅助类,和《多线程辅助类之CountDownLatch(三)》功能类似,都可以实现一组线程的相互等待。要说不通点,那就是CyclicBarrier在释放等待线程后可以重用,所以称它为循环 的 barrier。具体说明参照API,此处上代码:
package face.thread.CountDownLatch; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierDemo1 { public static void main(String[] args) { final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final CyclicBarrier start = new CyclicBarrier(3,new Runnable() { public void run() { try { System.out.println("准备就绪!"); Thread.sleep(1000); System.out.println("开始执行!"); } catch (InterruptedException e) { e.printStackTrace(); } } }); final CyclicBarrier end = new CyclicBarrier(3,new Runnable() { public void run() { System.out.println("------执行完毕-----!"); } }); for(int i = 0; i < 3;i++){ new Thread(new Runnable() { public void run() { try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() +"运动员准备就绪," + sdf.format(new Date())); start.await(); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() +"运动员结束比赛," + sdf.format(new Date())); end.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }).start(); } } }