Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use CountDownLatch

Shulou Source: shulou.com Published: 2022-06-01 23:09:02 09月15日 Update

This article mainly introduces "how to use CountDownLatch". In daily operation, I believe many people have doubts about how to use CountDownLatch. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use CountDownLatch"! Next, please follow the editor to study!

CountDownLatch is a very practical multithreaded control tool class. The commonly used methods are as follows:

CountDownLatch (int count) / / instantiates an inverted counter. Count specifies the number of counts countDown () / / count minus one await () / / wait. When the count is reduced to 0, all threads execute in parallel.

CountDownLatch is used frequently in many scenarios where I work. For example, our API interface requires response time within 200ms, but if an interface relies on multiple three-party / external services, the RT of the interface must be called serially for a long time. Therefore, the interface RT optimization scenario is most commonly used by individuals, and internal services are called in parallel.

For inverted counters, a typical scenario is rocket launch. Before the launch of the rocket, in order to ensure that it is foolproof, it is often necessary to test all kinds of equipment and instruments. Only after all the inspections have been completed can the engine ignite. Then, of course, multiple detection items can be carried out at the same time. Code implementation:

/ * * @ Author: Wang Qi 1124602935@qq.com * @ Date: 2019-5-4 0004 9:43 * @ Description: countdown timer example: rocket launch * / public class CountDownLatchDemo implements Runnable {static final CountDownLatch latch = new CountDownLatch (10); static final CountDownLatchDemo demo = new CountDownLatchDemo () @ Override public void run () {/ / Simulation check task try {Thread.sleep (new Random (). NextInt (10) * 1000); System.out.println ("check complete"); / / count minus one latch.countDown ();} catch (InterruptedException e) {e.printStackTrace () }} public static void main (String [] args) throws InterruptedException {ExecutorService exec = Executors.newFixedThreadPool (10); for (int iTuno; I

Tags: Threads interfaces methods rockets launches learning checks tasks scenarios multiple counters detections utility code instances more preparation help services frequent Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Linux MariaDB OPPO Reno