- CountDownLatch是什么
- CountDownLatch如何工作
- API
- countDownLatch应用场景例子
CounDownLatch这个类能够使一个线程等待其它线程完成各自的工作后再执行,例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。
使用场景:Zookeeper分布式锁,jmeter模拟高并发等。
CountDownLatch是通过一个计数器来实现的,计数器初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的初始值为线程的数量,每当一个线程已经完成了任务,然后在闭锁上等待的线程就可以恢复执行任务
APIcountDownLatch.countDown();//计数器减一 countDownLatch.await();//等待计数器为0countDownLatch应用场景例子
比如有两个线程,线程A执行需要3秒,线程B执行完需要5秒。现在我们是双核,可以同时执行这两个线程,5秒钟就能执行完成,然后一起回到主线程。
public class Thread_A implements Runnable{ CountDownLatch countDownLatch; Logger logger= LoggerFactory.getLogger(this.getClass()); public Thread_A(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @SneakyThrows @Override public void run() { logger.info("执行线程A:"+Thread.currentThread().toString()); Thread.sleep(3000); logger.info("执行线程A完成,准备执行主线程"); if(countDownLatch!=null){ countDownLatch.countDown(); } } }
public class Thread_B implements Runnable{ CountDownLatch countDownLatch; Logger logger= LoggerFactory.getLogger(this.getClass()); public Thread_B(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @SneakyThrows @Override public void run() { logger.info("执行线程B:"+Thread.currentThread().toString()); Thread.sleep(5000); logger.info("执行线程B完成,准备执行主线程"); if(countDownLatch!=null){ countDownLatch.countDown(); } } }
public class Test { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch=new CountDownLatch(2); new Thread(new Thread_A(countDownLatch)).start(); new Thread(new Thread_B(countDownLatch)).start(); countDownLatch.await(); System.out.println("执行主线程"); } }
输出:
16:01:15.233 [Thread-1] INFO com.zhongger.zchat.Thread_B - 执行线程B:Thread[Thread-1,5,main] 16:01:15.233 [Thread-0] INFO com.zhongger.zchat.Thread_A - 执行线程A:Thread[Thread-0,5,main] 16:01:18.249 [Thread-0] INFO com.zhongger.zchat.Thread_A - 执行线程A完成,准备执行主线程 16:01:20.238 [Thread-1] INFO com.zhongger.zchat.Thread_B - 执行线程B完成,准备执行主线程 执行主线程
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)