一、CountDownLatch

  jdk提供的一个同步辅助类,在完成一组在在其他线程中执行的操作前,允许一个或者多个其他的线程等待,通过调用 await() 方法阻塞,直到由于 countDown() 方法的调用而导致当前计数达到零,之后所有等待线程被释放。

二、计算多个线程执行时间

package com.example.demo.juc;

import java.util.concurrent.CountDownLatch;

/**
 * @author DUCHONG
 * @since 2019-01-17 14:18
 **/
public class LatchTest {

    public static void main(String[] args) {

        Long startTime=System.currentTimeMillis();
        CountDownLatch countDownLatch=new CountDownLatch(5);
        LatchThread latchThread=new LatchThread(countDownLatch);

        for(int j=1;j<=5;j++){
            new Thread(latchThread,"thread"+j).start();
        }

        try {
            countDownLatch.await();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        Long endTime=System.currentTimeMillis();

        System.out.println("over 耗时:"+(endTime-startTime));
    }

}

class LatchThread implements  Runnable{

    private CountDownLatch latch;
    public LatchThread(CountDownLatch l) {
        latch=l;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + "----" + i);
                    }
                }
            }
            finally {
                latch.countDown();
            }
        }
    }
}

 

相关文章:

  • 2021-07-25
  • 2021-10-31
  • 2021-10-14
  • 2021-07-02
  • 2021-07-14
猜你喜欢
  • 2021-11-05
  • 2021-12-16
  • 2021-08-30
  • 2021-06-28
  • 2019-10-08
  • 2022-12-23
相关资源
相似解决方案