多线程辅助类之CountDownLatch(三)
CountDownLatch信号灯是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。它可以实现多线程的同步互斥功能,和wait和notify方法实现功能类似,具体的实现代码如下:
package face.thread.CountDownLatch; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo3 { public static void main(String[] args) { int capaCity = 3; final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch startAnswer = new CountDownLatch(capaCity); final CountDownLatch end = new CountDownLatch(1); final CountDownLatch endAnswer = new CountDownLatch(capaCity); for(int i=0; i<capaCity; i++){ new Thread(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName() +"运动员准备就绪," + sdf.format(new Date())); try { startAnswer.countDown(); start.await(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }finally{ System.out.println(Thread.currentThread().getName() +"运动员结束比赛," + sdf.format(new Date())); endAnswer.countDown(); } } }).start(); } try { startAnswer.await(); System.out.println("比赛开始:" + sdf.format(new Date())); start.countDown(); endAnswer.await(); } catch (Exception e) { e.printStackTrace(); }finally{ System.out.println("比赛结束:" + sdf.format(new Date())); } } }
具体的说明参照Jdk Api,参照此例子加以理解