In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use the Java concurrency tool. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Text 1. What is a concurrency tool
The concurrency tool is a set of tool classes that are mainly used to control the execution flow of threads, such as blocking one thread to wait for other threads.
two。 Inverted counter CountDownLatch
Literally, it's an inverted latch (shuan, which can't be typed after playing zha for a long time)
To put it more colloquially, it means counting backwards. When the time is up, the latch will be opened.
Note: once opened, it can no longer be closed, that is, the state change of the CountDownLatch is permanently unrecoverable (remember this point, there will be a comparison later)
More officially: the inverted counter is used to block one (or some) thread to wait for the completion of tasks from multiple threads (whichever is the case, the above can be used for reference)
Several methods of CountDownLatch are listed below:
Construction method: public CountDownLatch (int count), where count is what we call the internal state (when count=0, the terminated state is reached, the blocked thread will be restored)
Modify state: public void countDown (), this method decrements the above count state, and each time it is executed, it is-1; (when count=0, the terminated state is reached, and the blocked thread is restored)
Wait: public void await (), which blocks the current thread and resumes execution until the count state changes to 0 (unless interrupted, where an interrupt exception is thrown)
Timeout wait: public boolean await (long timeout, TimeUnit unit), similar to the await above, except that you can set the timeout. If the timeout is over and it is still blocking, you can restore it directly.
Get the status value count:public long getCount () and get the value of count to see how many more times it can be decremented (mostly for debugging)
If you simulate the scene, here are three examples, and there must be others.
The first one is the counter, the most direct.
The second is to count the duration of the task.
The third is the multiplayer 5V5 game. When everyone has finished loading, the game will begin.
Let's take the third scene as an example, write an example: multiplayer game loading screen
Public class CountDownLatchDemo {public static void main (String [] args) throws InterruptedException {/ / 1. Construct an inverted counter, given a state value of 10 CountDownLatch latch = new CountDownLatch (10); System.out.println ("ready to load"); / / here we create 10 threads to simulate 10 players of the 5V5 game for (int I = 0; I)
< 10; i++) { new Thread(()->{/ / here we give a bit delay to simulate the network delay try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Thread.currentThread (). GetName () + "load 100%") / / 2. The countDown here is used to change the internal state of the inverted counter, each time-1 latch.countDown (); / / the current thread is not blocked, and the current thread is returned immediately after execution. Start ();} / / 3. This blocks the completion of the waiting state, that is, 10 becomes 0; latch.await (); System.out.println ("everyone loads finished, start the game");}}
The output is as follows:
Ready to load Thread-0 load 100%Thread-1 load 100%Thread-2 load 100%Thread-3 load 100%Thread-4 load 100%Thread-5 load 100%Thread-6 load 100%Thread-8 load 100%Thread-9 load 100%Thread-7 load all finished loading, start the game
The function of the inverted counter here is to block the main thread to wait for the other 10 child threads, and then resume the main thread when all are ready.
Its characteristic is that it can be used at one time and cannot be changed after reaching the termination state.
3. Upside-down counter upgrade CyclicBarrier [circular fence]
Loop fences, similar to inverted counters, are also used to block threads, but it focuses on recycling
The inverted counter can only be used once (this is the most obvious difference between them)
PS: guess it's called a circular fence rather than a circular latch, probably because the fence is more powerful than the latch, so it's more appropriate to call it a fence.
Officially, a circular fence is generally used to indicate that multiple threads are waiting for each other (blocking)
For example, if there are 10 threads, the await will have to wait; the fence will not open until the last thread await.
If a fence action is defined, the fence action is performed when the fence is opened
Fence action is the action to be performed after the fence is opened, which is specified by the Runnable parameter of the constructor. Optional parameters are described below.
This is the second difference between a circular fence and an inverted counter:
The loop fence emphasizes the collaborative relationship between multiple blocked threads (waiting)
The inverted counter emphasizes that a single (or multiple) thread is blocked to wait for the task of other threads to execute.
Let's take a look at a few methods inside the circular fence CyclicBarrier:
Construction method: public CyclicBarrier (int parties, Runnable barrierAction), the first indicates the number of threads waiting (blocking), and the second barrierAction is the fence action we mentioned above, that is, when the last thread is also blocked, the fence action will be triggered (this parameter is optional, if not, no action will be performed)
Wait: public int await (), blocking the current thread until the last thread is blocked
Timeout wait: public boolean await (long timeout, TimeUnit unit), similar to the await above, except that you can set the timeout
Get the number of threads currently waiting: public int getNumberWaiting (), that is, the number of threads that called the await method
Scene:
Big things become small, small things merge: to disassemble a large task into several small tasks, wait until the small tasks are completed, and then merge into one result
Multi-player game group war
The inverted counter above indicates the preparation before the start of the game (you only need to prepare once)
The circular fence here can represent the group battle work after the start of the game (can be fought many times).
Let's take a look at the following example: multiplayer game team battle screen
Public class CyclicBarrierDemo {public static void main (String [] args) throws InterruptedException {/ / 1. Create a circular fence, given the number of waiting threads 10 and the fence action CyclicBarrier barrier = new CyclicBarrier (10, ()-> {/ / fence action). When all threads are await, System.out.println will be triggered ("= everyone, let's start the group"); try {Thread.sleep (2000) } catch (InterruptedException e) {e.printStackTrace ();}}); System.out.println ("prepare for the first round of regiment warfare = ="); / / 2. Create 10 threads to simulate 10 players for (int I = 0; I
< 10; i++) { new Thread(()->{try {/ / players present System.out.println (Thread.currentThread (). GetName () + "= > the first wave, I'm ready") / / wait for others, wait for everyone to join the regiment (when everyone is ready to perform the fence action, this side will resume) barrier.await ();} catch (InterruptedException e) {e.printStackTrace ();} catch (BrokenBarrierException e) {e.printStackTrace () }). Start ();} / / 3. Query the current number of waiting threads. If it is not 0, the main thread continues to wait for while (barrier.getNumberWaiting ()! = 0) {Thread.sleep (1000);} System.out.println ("= the end of the first wave of group war = ="); / / 4. At this time, the second wave and the third wave of group warfare can also be carried out. (the loop fence can be triggered cyclically, and the inverted counter can only be triggered once.)}}
The output is as follows:
= = prepare for the first wave of group warfare = Thread-0= > first wave, I am ready for Thread-1= > first wave, I am ready for Thread-2= > first wave, I am ready for Thread-3= > first wave, I am ready for Thread-4= > first wave, I am ready for Thread-5= > first wave, I am ready for Thread-6= > first wave, I am ready for Thread-7= > first wave, I am ready for Thread-8= > first wave I am ready for the Thread-9= > first wave, I am ready for everyone, let's start the group, the first wave of group war is over. Semaphore Semaphore
Semaphores are mainly used to control multiple threads to access specified resources at the same time, such as database connection pooling. If the number exceeds a specified number, it blocks waiting.
Let's introduce several key methods of semaphores:
Construction method: public Semaphore (int permits, boolean fair). The first parameter is the number of permits, that is, the number of threads allowed to access at the same time, and the second parameter is fair or unfair mode (default is unfair)
In fair mode, whoever calls acquire first will access resources first, and FIFO will be first-in, first-out.
Unfair mode, allows queue jumping, if one thread just releases the license and another thread calls acquire, then that thread will jump the queue to access the resource)
Obtain a license: public void acquire (), if there is a license, return directly and decrease the number of licenses by 1; if no license is available, block the wait, or be interrupted
Try to get a license: public boolean tryAcquire (), which is similar to the acquire above, but will not be blocked or interrupted, because if no license is available, it will directly return to false
Release license: public void release (), release one license, and increment the number of licenses by 1
Get the number of licenses available: public int availablePermits (), which is generally used to debug
Scenario: database connection pooling
Semaphores are characterized by reusable licenses, so scenarios such as database connection pooling are suitable
We will not cite an example here, that is, multiple threads acquire and release will block if there is no license when obtaining permission, and return immediately if there is one.
5 differences
It is more convenient to read it with a table.
Distinguishing the number of times CountDownLatchCyclicBarrierSemaphore can be used multiple times (recycling) blocking of a single thread (multiple threads) to wait for the execution of other threads the mutual blocking of multiple threads exceeds the number of permits, which will block scenario 1. Counter 2. The execution time of the statistical task is 3. Wait for the start of the multiplayer game. Make a big deal small, and then merge 2. The group battle of the multiplayer game 1. Database connection pool
As you can see, the inverted counter is mainly used to indicate that a single thread is waiting for multiple threads, while the loop fence is mainly used to indicate the mutual waiting between multiple threads.
Summary
What is a concurrency tool: a concurrency tool is a set of tool classes that are mainly used to control the execution flow of threads, such as blocking one thread to wait for other threads
Inverted counter CountDownLatch: used to indicate that one (some) thread is blocked to wait for the completion of the task of multiple other threads
Circular fence CyclicBarrier: used to indicate mutual waiting and cooperation between multiple threads (blocking)
Semaphore Semaphore: indicates the number of permissions (threads) that are allowed to access specified resources at the same time
Difference:
Distinguishing the number of times CountDownLatchCyclicBarrierSemaphore can be used multiple times (recycling) blocking of a single thread (multiple threads) to wait for the execution of other threads the mutual blocking of multiple threads exceeds the number of permits, which will block scenario 1. Counter 2. The execution time of the statistical task is 3. Wait for the start of the multiplayer game. Make a big deal small, and then merge 2. The group battle of the multiplayer game 1. Database connection pool on "how to use Java concurrency tools" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.
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.