Semaphore (Traffic Signal mechanism) is required when we create a thread pool with a scalable size and need to run a limited number of threads concurrently in the thread pool ), semaphore is usually used to limit the number of threads that can access certain resources (physical or logical). It is a count semaphores. Conceptually, semaphores maintain a license set. If necessary, each acquire () is blocked before the license is available, and then the license is obtained. Each release () adds a license, which may release a recipient that is being blocked.
When creating a thread in the thread pool and running it, each thread must obtain a license from the semaphore to ensure that this item can be used. After the thread ends, the thread returns to the pool and returns the license to the semaphore. This allows other threads to obtain this item. Note that the synchronization lock cannot be maintained when acquire () is called, because this will prevent the thread from returning to the pool. Semaphores encapsulate the required synchronization to restrict access to the pool, which is separated from the synchronization required to maintain the consistency of the pool. The following is an example:
[Java]
Public class SemaphoreTest {
Public static void main (String [] args ){
ExecutorService service = Executors. newCachedThreadPool ();
Final Semaphore sp = new Semaphore (3 );
For (int I = 0; I <5; I ++ ){
Runnable runnable = new Runnable (){
Public void run (){
Try {
Sp. acquire ();
} Catch (InterruptedException e1 ){
E1.printStackTrace ();
}
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Enter, current" + (3-sp.availablePermits () + "concurrent ");
Try {
Thread. sleep (long) (Math. random () * 10000 ));
} Catch (InterruptedException e ){
E. printStackTrace ();
}
System. out. println ("Thread" + Thread. currentThread (). getName () +
"Coming soon ");
Sp. release ();
// The following code is sometimes inaccurate because it does not merge atomic units with the above Code
System. out. println ("Thread" + Thread. currentThread (). getName () +
"You have left, and it already exists" + (3-sp.availablePermits () + "concurrent ");
}
};
Service.exe cute (runnable );
}
}
}
This example defines a newCachedThreadPool. In this Pool, five threads are created simultaneously using the for loop. Now, Using Semaphore, you can create one that only allows three threads to run concurrently in the thread Pool, sp. acquire () indicates that a thread obtains a signal lamp and starts to run. release () returns this signal lamp so that the remaining threads can get the signal lamp to run, sp. availablePermits () indicates how many of the current traffic signal libraries can be used. Because three traffic signals are defined in this example, 3-sp.availablepermits () it indicates how many threads are currently running concurrently. The running result of the preceding example is as follows:
[Java]
Thread pool-1-thread-1 entry, there are currently 2 concurrency
Thread pool-1-thread-2 entry, there are currently 2 concurrency
Thread pool-1-thread-3 enters. Currently, three concurrent threads exist.
Thread pool-1-thread-1 is about to exit
Thread pool-1-thread-1 has left, and two concurrent threads exist.
Thread pool-1-thread-4 entry, there are currently 3 Concurrent
Thread pool-1-thread-3 is about to exit
Thread pool-1-thread-3 has left, and two concurrent threads exist.
Thread pool-1-thread-5 Entry, there are currently 3 Concurrent
Thread pool-1-thread-2 is about to exit
Thread pool-1-thread-2 has left, and two concurrent threads exist.
Thread pool-1-thread-4 is about to exit
Thread pool-1-thread-4 has left, and one concurrency exists.
Thread pool-1-thread-5 is about to exit
Thread pool-1-thread-5 has left, and 0 concurrent threads exist.
Semaphore is used as a mutex lock:
When the semaphore is initialized to 1, it can be used as a mutually exclusive lock with only one license. This is also known as a binary semaphore because it can only have one available license or zero available license. When using this method, the biggest difference from the traditional mutex lock is that when the lock is released, it is not necessary to release the lock object, or it can be released by other objects, because semaphores do not have ownership. This can be useful in some specialized contexts (such as deadlock recovery.
There are two methods to construct Semaphore:
First:
[Java]
Semaphore (int permits) // create a Semaphore with the given number of licenses and unfair fair settings.
The signal lamp created by the first constructor is random and has no sequence. For example, in the preceding example, a signal lamp is released after one of the first three threads is completed, the remaining two threads will run with a random thread getting the signal lamp.
Second:
[Java]
Semaphore (int permits, boolean fair) // create a Semaphore with the given number of licenses and given fair settings
The second constructor can choose to accept a fair parameter. When set to false, this class does not guarantee the order in which the thread obtains the license. In particular, intrusion is allowed, that is, you can assign a license to the thread that calls acquire () before the waiting thread. Logically, that is, the new thread places itself in the header of the waiting thread queue. When fairness is set to true, semaphores ensure that any thread that calls the acquire () method is processed in the order they call these methods (that is, first-in-first-out and first-out) to select a thread and obtain a license. Note that FIFO sorting must be applied to the specified internal execution points in these methods. Therefore, a thread may have called acquire () before another thread, but it has reached the sorting point after the thread, and it is similar when returning from the method. Note that the non-synchronous tryAcquire () method does not use fair settings, but uses any available licenses.
Generally, semaphores used to control resource access should be initialized fairly to ensure that all threads can access resources. When semaphores are used for synchronization control of other types, the throughput advantage of unfair sorting is usually more important than fair considerations.