Introduction to Java semaphores Semaphore
The semaphore class also appears in java1.5, which is located in the java. util. concurrent package.
First, let's take a look at his document explanation:
A count semaphore. In terms of concept, semaphores maintain a license set. If necessary, eachacquire()And then obtain the license. Eachrelease()Add a license to release a blocked recipient. However, do not use the actual license object,SemaphoreIt only counts available license numbers and takes corresponding actions. There are two very important methods: acquire and release.
Now let's take a look at the introduction of these two methods.
public void acquire() throws InterruptedException
-
From this semaphore, a license is obtained, and the thread is blocked until a license is provided. Otherwise, the thread is interrupted. Get a license (if one is provided) and return immediately, reduce the number of available licenses by 1.
If no license is available, you are prohibited from using the current thread for Thread Scheduling purposes and putting it in sleep state before one of the following two cases:
- Some other threads call this semaphore
release()Method, and the current thread is the next thread to be allocated with a license; or some other threads interrupt the current thread.If the current thread: