The semaphore of Semaphore of JAVA multithreading is explained in detail
- 2020-05-30 20:18:11
- OfStack
java Semaphore
Introduction to the
Semaphores (Semaphore), sometimes referred to as semaphores, are a facility used in a multithreaded environment to coordinate threads so that they can properly and rationally use common resources.
One count semaphore. Conceptually, the semaphore maintains a license set. If necessary, each acquire() is blocked before the license becomes available, and then the license is obtained. Each release() adds a license, potentially freeing an acquirer that is blocking. Instead of using actual license objects, however, Semaphore simply counts the number of licenses available and ACTS accordingly. The thread that gets the semaphore can enter the code, otherwise it waits. Obtain and release access permissions through acquire() and release().
concept
There are two types of Semaphore: single value and multi-value. The former can only be obtained by one thread, while the latter can be obtained by several threads.
Take the example of a parking lot operation. For the sake of simplicity, let's say there are only three parking Spaces in the parking lot, and 1 starts with three empty parking Spaces. If five cars arrive at the same time, the gatekeeper allows three of them to enter unimpeded, then drops the barrier, and the rest must wait at the entrance, and all the others must wait at the entrance. At this time, there is a car to leave the parking lot, the doorman after that, open the car block, put in 1, if leave two, can put in two, and so on and so on.
In this parking system, the parking space is a public resource, each car is like a thread, and the janitor ACTS as a semaphore.
Further, the semaphore has the following characteristics: the semaphore is a non-negative integer (number of parking Spaces), and all threads (vehicles) that pass through it will subtract 1 from that integer (for the purpose of using resources). When the integer value is zero, all threads that attempt to pass through it will be in a waiting state. On the semaphore we define two operations: Wait (wait) and Release (release). When a thread calls an Wait (wait) operation, it either passes and subtracts the semaphore by 1, or it waits until the semaphore is greater than 1 or times out. The Release (release) actually performs the add operation on the semaphore corresponding to the vehicle leaving the parking lot. This operation is called "release" because the add operation actually releases the resource guarded by the semaphore.
In Java, you can also set whether the semaphore is in fair mode, so that if it is executed fairly, the threads will execute in the order in which they arrived (FIFO), or, if not, later requests may be placed at the head of the queue.
JDK is defined as follows:
Semaphore(int permits, boolean fair)
Create Semaphore with a given number of permissions and a given fair setting.
Semaphore is currently used extensively in multithreaded environments, where OS semapore is a very important concept and has applications in process control. The Java concurrency library, Semaphore, can easily do semaphore control, Semaphore can control the number of resources that can be accessed at the same time, get one license through acquire(), wait if none is available, and release() releases one license. For example, under Windows you can set the maximum number of client accesses to a Shared file.
The function that Semaphore realizes is similar to toilet has 5 pits, if have 10 people to want to go to toilet, so can have how many people go to toilet only at the same time? There can only be five people who can take it, and when any one of the five gets out of the way, one of the other five people who are waiting can take it. Depending on the parameter options passed in when constructing the Semaphore object, one of the five people who are waiting can either get the priority opportunity at random or in a first come, first served order. The Semaphore object of a single semaphore can perform the function of a mutex, and the "lock" can be acquired by one thread and then released by another thread, which can be used in some situations of deadlock recovery.
Code sample
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* DateTime: 2015 years 1 month 1 day In the afternoon 6:41:01
*
*/
public class SemaPhore {
public static void main(String[] args) {
// The thread pool
ExecutorService exec = Executors.newCachedThreadPool();
// only 5 Two threads access at the same time
final Semaphore semp = new Semaphore(5);
// simulation 20 Client access
for (int index = 0; index < 50; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {<span id="transmark"></span>
// To obtain permission
semp.acquire();
System.out.println("Accessing: " + NO);
Thread.sleep((long) (Math.random() * 6000));
// After the visit, release
semp.release();
//availablePermits() Refers to how many current semaphores are available in the library
System.out.println("-----------------" + semp.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
// Exit thread pool
exec.shutdown();
}
Thank you for reading, I hope to help you, thank you for your support of this site!