In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use Semaphore". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Semaphore.
Basic information
Name: Semaphore
English name: (count) semaphore
Date of birth: JDK 1.5
Place of origin: JUC (java.util.concurrent)
Purpose: a synchronizer in Java, unlike CountDownLatch and CyclicBarrier, Semaphore is used to manage licenses. When a thread calls the acquire () method, if there is no license, the thread will block waiting until the license is available. The license uses the release () method to publish (issue a license), and when the acquire () method is called, the license is reduced and the following code continues to execute if there is a certificate, and if there is no certificate, it can only block waiting for the license, while Semaphore declares the maximum number of licenses when it is created.
Professional skills
My professional skill is "management certificate", using this skill can easily achieve the "flow limit" function.
What is current restriction?
For example, the May Day short holiday is approaching, when there will be a large number of people visiting various scenic spots, but the capacity of each scenic spot is limited. For example, the Datang Furong Garden in Greater Xi'an has a daily carrying capacity of 60,000 people, that is to say, a maximum of 60,000 people can visit here every day, but a lot of people will come on May Day, for example, 100000 people will come suddenly, so at this time we can only "restrict the flow" and wait in line to enter the park.
In other words, Datang Furong Garden will let 60,000 people go in and play first, and the rest will wait in line at the door. When someone comes out of it, another queue will be allowed to enter. The staff will always control the number to less than 60,000, and the purpose of this is to make the players have a good experience, so as not to cause some accidents, such as a stampede, which, to a certain extent, ensures social stability and facilitates the establishment of a good reputation of the scenic spot and the normal operation in the future. The behavior of queuing to limit the maximum number of people is "flow restriction".
To take another example, for example, in terms of the limit number of a vehicle, it is also a common scene of current restriction. The advantage of this is that, on the one hand, it can protect the environment with as little carbon emissions as possible, and on the other hand, it can effectively alleviate the congestion during rush hours. Especially in Greater Xi'an, it is hard to imagine what the traffic jam would be like if there was no limit on the number. (PS: to make an otherwise unrich life even worse.)
Let's go back to the program from life examples, and suppose that a program can only serve 10W people, and suddenly one day, because of a hot event, the number of visits to the system increases rapidly to 50W in a short period of time. Then the direct result is that the system crashes, and no one can use the system. Obviously, only a small number of people can use it far more in line with our expectations than no one can use it. So we are going to use "current restriction" at this time.
Using Semaphore to realize current limit
Semaphore can set the number of certificates when it is created, which is equivalent to setting the maximum value of the current limit, and then issue the certificate through the release () method, and block and wait for the certificate through the acquire () method, so as to achieve the current limit function by controlling the certificate.
Project experience
Next, we use code to demonstrate the use of Semaphore. Let's take the current limit of the parking lot as an example. Assume that there are only 2 parking spaces in the whole parking lot (although there are few parking spaces, but it is enough to explain the problem), but there are 5 cars coming to park. Obviously, the parking space is not enough. At this time, we need to ensure that the parking lot can only have 2 vehicles at most. Next, we use Semaphore to achieve the vehicle flow restriction function. The specific implementation code is as follows:
Import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; / * Author: Leige * By:Java Chinese Community * / public class SemaphoreExample {/ / create semaphore static Semaphore semaphore = new Semaphore (2); public static void main (String [] args) {/ / create 5 fixed threads ExecutorService threadPool = Executors.newFixedThreadPool (5) / / define the execution task Runnable runnable = new Runnable () {@ Override public void run () {/ / get the name of the current thread String tname = Thread.currentThread () .thread () System.out.println (String.format ("veteran driver:% s, queue outside the parking lot, time:% s", tname, new Date ()); try {/ / executes this line, letting all threads queue first to enter the parking lot Thread.sleep (100) / / execute blocking semaphore.acquire (); System.out.println ("Old driver:% s, entered the parking lot, time:% s", tname, new Date ()); Thread.sleep (1000) System.out.println (String.format ("veteran driver:% s, leave the parking lot, time:% s", tname, new Date ()); / / release lock semaphore.release ();} catch (InterruptedException e) {e.printStackTrace () }; / execute Task 1 threadPool.submit (runnable); / execute Task 2 threadPool.submit (runnable); / execute Task 3 threadPool.submit (runnable); / / execute Task 4 threadPool.submit (runnable) / / execute task 5 threadPool.submit (runnable); / / close threadPool.shutdown () after thread pool task has been executed;}}
The execution result of the above code is as follows:
From the above results, we can see that when five cars need to enter the parking lot at the same time, because there are only two parking spaces in the parking lot, the parking lot can only hold a maximum of two cars. At this time, we successfully achieve the current limit function through Semaphore's acquire method (blocking waiting) and release method (issuing a certificate), so that the number of vehicles in the parking lot is always controlled below 2 vehicles (equal to or less than 2 vehicles).
Personal evaluation
There are two ways for me (Semaphore) to implement certificate control, one is fair mode and the other is unfair mode. Of course, for the performance consideration of execution, I adopt an unfair method by default, which specifically implements the visible source code:
Public Semaphore (int permits) {sync = new NonfairSync (permits); / / unfair mode}
On the fair model and the unfair model
The so-called fair mode determines the order of obtaining licenses in the order in which acquire () is called, and the fair mode follows the first-in, first-out (FIFO) principle, while the non-fair mode is preemptive, that is, it is possible that a new acquisition thread gets the license just when a license is released, and there are waiting threads ahead.
It is obviously better to use unfair mode because it issues licenses to threads that are just ready, rather than "calling" in order.
Use fair mode
Of course, you can manually choose to run Semaphore,Semaphore in fair mode. Two constructors are provided, and the source code is as follows:
Public Semaphore (int permits) {sync = new NonfairSync (permits);} public Semaphore (int permits, boolean fair) {sync = fair? New FairSync (permits): new NonfairSync (permits);}
If you want to use fair mode, you can use the second constructor Semaphore (int permits, boolean fair). Setting the fair value to true is fair mode to obtain the certificate.
Other supplements
I have also provided some other ways to achieve more functionality, as follows:
Int availablePermits (): returns the number of licenses currently available in this semaphore.
Int getQueueLength (): returns the number of threads waiting for a license.
Boolean hasQueuedThreads (): whether a thread is waiting for a license.
Boolean isFair (): queries whether Semaphore uses fair mode or unfair mode, and returns true if this semaphore uses fair mode.
Void release (int permits): releases a given number of licenses and returns them to the semaphore.
TryAcquire (): get a license from this semaphore, which can only be used when invoked.
TryAcquire (int permits): get a given number of licenses from this semaphore, all of which are available only when called.
TryAcquire (int permits, long timeout, TimeUnit unit): gets a given number of licenses from this semaphore if all are available within the given wait time and the current thread has not yet interrupted.
TryAcquire (long timeout, TimeUnit unit): obtain permission from this semaphore if it is available within a given wait time and the current thread has not yet reached the interrupted.
Void reducePermits (int reduction): reduces the number of licenses available by reduction, which is the protected method.
Collection getQueuedThreads (): returns a collection of all threads waiting for a license, which is the protected method.
Thank you for your reading, the above is the content of "how to use Semaphore", after the study of this article, I believe you have a deeper understanding of how to use Semaphore, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.