- import java.util.concurrent.CountDownLatch;
- public class LatchDriverDemo {
- private static final int N = 5;
- public static void main(String[] args) throws InterruptedException {
- // 用于向工作线程发送启动信号
- CountDownLatch startSignal = new CountDownLatch(1);
- // 用于等待工作线程的结束信号 CountDownLatch
- CountDownLatch doneSignal = new CountDownLatch(N);
- for (int i = 0; i < N; i++)
- // 创建启动线程
- new Thread(new LatchWorker(startSignal,doneSignal),"t"+i).start();
- // 得到线程开始工作的时间
- long start = System.currentTimeMillis();
- //主线程,递减开始计数,让所有线程开始工作
- startSignal.countDown();
- //主线程开始阻塞,等待其他线程完成
- startSignal.await();
- long end = System.currentTimeMillis();
- //System.out.println("All Work Take Time : "+ (end - start)/1000.0+"s" );
- System.out.println(end+" "+start);
- }
- }
- import java.util.concurrent.CountDownLatch;
- public class LatchWorker implements Runnable{
- private final CountDownLatch startSignal;
- private final CountDownLatch doneSignal;
- public LatchWorker(CountDownLatch startSignal,CountDownLatch doneSignal){
- super();
- this.startSignal = startSignal;
- this.doneSignal = doneSignal;
- }
- @Override
- public void run() {
- try {
- startSignal.await();
- dowork();
- doneSignal.countDown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- private void dowork() {
- // TODO Auto-generated method stub
- int a = 0 ;
- for (int i = 0; i < 10000; i++) {
- a += 1;
- }
- System.out.println(Thread.currentThread().getName()+"="+a);
- }
- }