Countdownlatch synchronization tool class usage details
Countdownlatch instructions are for your reference. The specific contents are as follows
Countdownlatch is a Java util. The concurrent package is the next synchronization tool class, which allows one or more threads to wait until a set of operations are completed in other threads.
The usage of countdown latch is very simple. I saw the following example on the Internet. It's very appropriate. I'll post it here
Here are the results of the run
You can see that we control the execution order of threads through the use of countdownlatch.
In the above code, we use the await () method and the countdown () method. Let's verify their respective functions.
First, verify the await () method. End. In the main method Await() is commented out, and the following is the operation result after comment out
You can see that the main thread does not wait for the end of the thread representing the player, and directly declares that the game is over! A game that ends at the beginning --
As you can see here, the await () method is blocking
Next, let's verify the countdown method, which will represent the end. In the player thread Countdown(), the following is the running result
The program has been running. All the players have reached the end, but the referee just doesn't publicize the end of the game. What is he waiting for?
We guess that the countdown () method can wake up the blocked thread.
Then we may ask, since it can wake up the blocked thread, can't we wake up the blocked main thread by calling the countdown () method only once?
Let's try to cancel the comment of coutdown () above and create a contestant again. The code is as follows
The main method is also modified as follows to create two different players
Run it. Here's the result
The main program has been blocked and has not been awakened. The referee has to go to the toilet for a long time!
In this way, countdown () does not wake up the thread directly. It is a bit like a counter and countdown.
Check the API documentation. Sure enough, we added parameter 2 to the constructor, so we need to call countdown () twice to end Await() wakes up blocked threads.
To sum up,
1、CountDownLatch end = new CountDownLatch(N); // When constructing an object, you need to pass in parameter n
2、end. Await () can block the thread until end. Net is called n times The countdown() method releases the thread
3、end. CountDown () can be called in multiple threads. The number of computation calls is the sum of all thread calls.
In the next blog, I will explain how countdownlatch works from the source level.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.