SoFunction
Updated on 2025-03-08

Detailed explanation of JAVA multi-threaded semaphore instance

java Semaphore

Introduction

Semaphore, sometimes called signal light, is a facility used in a multi-threaded environment. It is responsible for coordinating various threads to ensure that they can use public resources correctly and reasonably.

A counting semaphore. Conceptually, semaphore maintains a license set. If necessary, each acquire() will be blocked before the license becomes available before it is obtained. Each release() adds a permission, which may release a blocking acquirer. However, without using the actual license object, Semaphore only counts the available license numbers and takes corresponding actions. The thread that gets the semaphore can enter the code, otherwise it will wait. Get and release access permissions through acquire() and release().

concept

Semaphore is divided into two types: single value and multi-value. The former can only be obtained by one thread, and the latter can be obtained by several threads.

Take a parking lot as an example. For simplicity, assuming there are only three parking spaces in the parking lot, all three parking spaces are empty at the beginning. At this time, if five cars come at the same time, the janitor will allow three of them to enter without any obstacles, and then put them down and stop them. The remaining cars must wait at the entrance, and the subsequent cars will have to wait at the entrance. At this time, a car left the parking lot. After the janitor learned about it, he opened the car and stopped it and put one. If two more cars left, two more could be put in, and this was repeated.

   In this parking lot system, parking spaces are public resources, each car is like a thread, and the gatekeeper plays the role of semaphore.

Further, the characteristics of the semaphore are as follows: the semaphore is a non-negative integer (number of parking spaces), and all threads passing through it (vehicle) will subtract the integer by one (passing it is of course for the use of resources), and when the integer value is zero, all threads trying to pass through it will be in a waiting state. In terms of semaphores, we define two operations: Wait and Release. When a thread calls the Wait operation, it either passes and then subtracts the semaphore by one, or waits until the semaphore is greater than one or timeout. Release is actually performing an addition operation on the semaphore, which corresponds to the vehicle leaving the parking lot. This operation is called "release" because the addition operation actually releases resources guarded by the semaphore.

In Java, it is also possible to set whether the semaphore is in fair mode. If executed in fair mode, the thread will be executed in the order of arrival (FIFO). If it is not fair, the requested one may be placed at the head of the queue.
The definition in JDK is as follows:

        Semaphore(int permits, boolean fair)

Create a Semaphore with a given permission number and a given fair settings.

Semaphore is currently spread and used in a multi-threaded environment. The semaphore of the operating system is a very important concept and is used in process control. The Java concurrency library Semaphore can easily complete semaphore control. Semaphore can control the number of resources that can be accessed simultaneously, obtain a license through acquire(), wait if there is no, and release() releases a license. For example, under Windows, you can set the maximum number of client accesses to shared files.

The functions implemented by Semaphore are similar to all 5 pits in the toilet. If 10 people have to go to the toilet, then how many people can only go to the toilet at the same time? At the same time, only 5 people can occupy it. When any of the five people moves aside, one of the other 5 people waiting can occupy it. In addition, among the 5 people waiting, you can get the priority chance at random, or you can get the chance in the order of first come and then arrive, depending on the parameter options passed in when constructing the Semaphore object. A single semaphore object can implement the function of a mutex, and it can be obtained by one thread and released by another thread. This can be applied in some cases of deadlock recovery.

Code Example

import ; 
import ; 
import ; 
 
 
/**
  * DateTime: January 1, 2015 at 6:41:01 pm
  *
  */ 
public class SemaPhore { 
  public static void main(String[] args) { 
    // Thread pool    ExecutorService exec = (); 
    // Only 5 threads can access it at the same time    final Semaphore semp = new Semaphore(5); 
    // Simulate 20 client access    for (int index = 0; index < 50; index++) { 
      final int NO = index; 
      Runnable run = new Runnable() { 
        public void run() { 
          try {<span ></span> 
            // Obtain a license            (); 
            ("Accessing: " + NO); 
            ((long) (() * 6000)); 
            // After access, release            (); 
            //availablePermits() refers to how many of the current signal light library can be used            ("-----------------" + ());  
          } catch (InterruptedException e) { 
            (); 
          } 
        } 
      }; 
      (run); 
    } 
    // Exit the thread pool    (); 
  } 

Thank you for reading, I hope it can help you. Thank you for your support for this site!