In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how to use Java highly concurrent programming CountDownLatch, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
What is CountDownLatch?
CountDownLatch is implemented through a counter whose initial value is the number of threads. Every time a thread finishes executing, the value of the counter is subtracted by 1. When the value of the counter is 0, all threads have finished executing, and then the thread waiting on the lock (the thread calling the await method) can resume work.
Application scenario
What can CountDownLatch be used for? What are the application scenarios? Is there any application scenario in the actual project? This should be what everyone is more concerned about. Let's first take a look at the example of how the application is provided on the official website. Https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html officially provided two demo. I directly turned it into a picture. By the way, this code is recommended to the URL of the image https://www.dute.org/code-snapshot is quite useful.
The official website demo1
★ The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed; The second is a completion signal that allows the driver to wait until all workers have completed. "
The first start signal (startSignal) will stop any worker (worker) from starting work before the driver arrives. To put it bluntly, the workers can't work without the driver.
The second is the completion signal (doneSignal), which allows the driver to Driver to wait until all workers are finished. To put it bluntly, the driver has to wait until all the workers are finished.
The official website demo2
★ Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. "
Another typical use is to split a large task into N parts and let multiple threads (Worker) execute. Each thread (Worker) subtracts its own part of the counter by 1. When all the sub-parts are completed, the Driver continues to execute downward. Just like the assembly line of Foxconn mobile phone processing, the assembly line of Foxconn mobile phone needs to cooperate with each other. Worker after assembly line, each doing its own job. Some assembly lines are covered with film, some are screwed, some are quality inspection, some are charged, and some are covered with film. When these assembly lines are finished, a mobile phone will be assembled.
The above two are the official demo, and here are two more chestnuts that we can use in our development:
Multiple threads wait: simulates concurrency, allowing concurrent threads to execute together.
Sometimes we write an interface to test it to see what its maximum concurrency is. Of course, we can use Jmeter for stress testing, but sometimes we don't want to download the tool, so we can do it with CountDownLatch.
/ * * @ author: official account: java Finance * / public class TestCountDownLatch2 {public static void main (String [] args) throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch (1); for (int I = 0; I
< 5; i++) { new Thread(() ->{try {/ / all requests are blocked here, waiting for countDownLatch.await (); / / call the test interface System.out.println (Thread.currentThread (). GetName () + "start execution.") ;} catch (InterruptedException e) {e.printStackTrace ();}}) .start ();} / make all requests ready for Thread.sleep (2000); / / Let all requests request countDownLatch.countDown () }}
Through CountDownLatch.await (), we let multiple participant threads block waiting after startup, and then call CountDownLatch.countdown () in the main thread to reduce the count to 0 and let all threads execute down together, thus achieving the purpose of simultaneous execution of multiple threads at the same time to simulate concurrent requests.
A single thread waits: after multiple threads (tasks) have completed, summarize and merge
/ * * @ author: official account: java Finance * / public class TestCountDownLatch2 {public static void main (String [] args) throws InterruptedException {int count = 3; CountDownLatch countDownLatch = new CountDownLatch (count); for (int I = 0; I
< count; i++) { final int index = i; new Thread(() ->{try {Thread.sleep (1000 + ThreadLocalRandom.current (). NextInt (1000)); System.out.println ("finish" + index + Thread.currentThread (). GetName ());} catch (InterruptedException e) {e.printStackTrace () } finally {countDownLatch.countDown ();}}) .start ();} countDownLatch.await (); / / the main thread is blocking. When the counter = = 0, the main thread is awakened to execute. System.out.println ("main thread: summarizing the results after all tasks have been run");}}
This kind of scenario should be used the most. For example, when we open an e-commerce personal center page, we need to call the user information interface, user order interface, user member information and other interfaces, and then merge them to the front end together. Assume that the longest time of each interface is 1s, and if we call it synchronously, the maximum time is 3s. If we use asynchronous calls, then merge the results. So the biggest time-consuming is 3s. After each interface call returns data, the countDown method is called to subtract the counter by 1. When the counter is reduced to 0, the thread will wake up the main thread and let it continue to go down.
Principle of CountDownLatch implementation
CountDownLatch is a counter implemented through the state field of AQS. The initial value of the counter (the value of state) is the number set by new CountDownLatch. Each time countDown is called, the value of state will be subtracted by 1. Finally, when a thread reduces the value of state to 0, it will wake up the thread that called await () to block and wait. CountDownLatch overrides the tryReleaseShared method so that only if the state field is set to 0, that is, if tryReleaseShared returns true, the doReleaseShared method will be executed to wake up the thread that called await.
Public final boolean releaseShared (int arg) {if (tryReleaseShared (arg)) {doReleaseShared (); return true;} return false;} rotected boolean tryReleaseShared (int releases) {/ / Decrement count; signal when transition to zero for (;;) {int c = getState (); if (c = 0) return false Int nextc = Cmurl; if (compareAndSetState (c, nextc)) return nextc = = 0;}} the above is how to use CountDownLatch of Java high concurrency programming. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.