In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
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 to answer the doubts about "how to use CountDownLatch"! Next, please follow the editor to study!
"CountDownLatch"
Imagine a scenario where we need to wait for some thread to finish executing before executing the code of the main thread.
One might say, simply, use the join () method to wait for the thread to finish execution before executing the main thread. The implementation code goes like this:
/ / create thread 1 Thread T1 = new Thread (new Runnable () {@ Override public void run () {/ / do something}}); t1.start (); / / create thread 2 Thread T2 = new Thread (new Runnable () {@ Override public void run () {/ / do something}}); t2.start () / / wait for thread 1 and thread 2 to finish executing t1.join (); t2.join ()
Of course, this is also possible if you are using Thread to perform tasks. However, in a real (coding) environment, we would not use Thread to perform multitasking. Instead, we would use a thread pool to perform multitasking, which avoids the performance overhead caused by repeated thread startup and destruction. The implementation code is as follows:
/ / create a thread pool with a fixed number of threads ExecutorService executorService = Executors.newFixedThreadPool (2); / / Task 1 executorService.submit (new Runnable () {@ Override public void run () {/ / do something}}); / / Task 2 executorService.submit (new Runnable () {@ Override public void run () {/ / do something}})
So here comes the problem: there is no join () method in the thread pool, so how do you wait?
At this time, we will send our general "CountDownLatch".
I have Admiral Pan Feng, who can cut Hua Xiong. A few seconds out, Pan Feng. Pawn.
Wait, director, I think the plot should be like this.
CountDownLatch usage
In order to implement the logic of waiting for all thread pools to execute before executing the main thread, I decided to use the famous class CountDownLatch under AQS (AbstractQueuedSynchronizer, Abstract synchronization Framework) to implement this function. The specific implementation code is as follows:
Public static void main (String [] args) throws InterruptedException {/ / create CountDownLatch CountDownLatch countDownLatch = new CountDownLatch (2); / / create a thread pool with a fixed number of threads ExecutorService executorService = Executors.newFixedThreadPool (2) / / Task 1: executorService.submit (new Runnable () {@ Override public void run () {/ / do something try {/ / Let this task execute 1.2s Thread.sleep (1200);} catch (InterruptedException e) {e.printStackTrace () } System.out.println ("I am Task one"); countDownLatch.countDown ();}}) / / Task 2 executorService.submit (new Runnable () {@ Override public void run () {/ / do something try {/ / Let this task execute 1.2s Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () } System.out.println ("I am Task 2"); countDownLatch.countDown ();}}); / / wait for task execution to complete countDownLatch.await (); System.out.println ("Program execution completed ~");}
The results of the above procedures are as follows:
As can be seen from the above results, the execution of the main thread waits for the completion of both Task 1 and Task 2.
Principle of CountDownLatch implementation
In CountDownLatch, count down means countdown, and latch means latch. The overall meaning can be understood as the countdown of the door bolt, it seems to be a bit "321, sesame open the door" feeling, the role of CountDownLatch is just like this.
CountDownLatch needs to pass in an integer when it is created, and the main thread needs to suspend and wait until the integer "countdown" to 0, and the main thread can not continue to execute until all other threads have executed.
CountDownLatch execution process
The implementation of CountDownLatch creates and maintains an integer counter of type volatile internally. When the countDown () method is called, the integer counter-1 is attempted. When the wait () method is called, the current thread determines whether the integer counter is 0. If it is 0, it continues to execute. If not, the current thread enters a waiting state until a thread sets the counter to 0. The thread waiting in the await () method is awakened to continue execution.
The common CountDownLatch method / / thread is suspended until the count value is 0 before continuing to execute public void await () throws InterruptedException {}; / / is similar to await (), except that the execution of public boolean await (long timeout, TimeUnit unit) throws InterruptedException {} will continue if the count value does not change to zero after waiting for a certain amount of time; / / subtract the count value by 1 public void countDown () {} At this point, the study on "how to use CountDownLatch" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.