本文主要是介绍CountDownLatch闭锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java并发库提供了CountDownLatch类来实现这个功能。
CountDownLatch类是一个同步工具类,在完成某些运算时,只有其他所有的运算全部完成,当前运算才继续执行。
下面是一个案例来说明CountDownLatch:
说明:当前有 5 个线程做运算处理,主线程要计算这 5 个子线程执行所消耗的时长。那么CountDownLatch在主线程中一直等待这这 5 个线程执行完后,才执行主线程。每个子线程执行完后执行latch.countDown();也就是线程-1 的操作,直到线程数为 0 的时候,主线程才会执行,主线程执行latch.await();等待着。
public class CountDownLatchDemo {public static final Integer THREAD_NUM = 5;public static void main(String[] args) {CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);LatchDemo latchDemo = new LatchDemo(countDownLatch);long startTime = System.currentTimeMillis();for (int i = 0; i < THREAD_NUM; i++) {new Thread(latchDemo).start();}try {countDownLatch.await();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("消耗时间:" + (System.currentTimeMillis() - startTime)+ "ms");}
}
class LatchDemo implements Runnable {private CountDownLatch latch;public LatchDemo(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {synchronized (this){try {for (int i = 0; i < 50000; i++) {if (i % 2 == 0){System.out.println(i+ "是偶数");}}} finally {latch.countDown();}}}
}
这篇关于CountDownLatch闭锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!