Semaphore Detailed Explanation of Java Concurrent Programming

foreword

SemaphoreCurrently widely used in multi-threaded environment, semaphore is a very important concept, which has applications in process control. The Semaphore of the Java concurrency library can easily complete the semaphore control. The Semaphore can control the number of a resource that can be accessed at the same time, by acquire() obtaining a license, waiting if not, and release()releasing a license. For example, under Windows, you can set the maximum number of clients to access shared files.

Construction method

The Semaphore class is located under the java.util.concurrent package, which provides two constructors:

//参数permits表示许可数目,即同时可以允许多少线程进行访问
public Semaphore(int permits) {
    
              
    sync = new NonfairSync(permits);
}

//这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
public Semaphore(int permits, boolean fair) {
    
        
    sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}

common method

Several important methods, the first is the acquire (), release () method:

public void acquire() throws InterruptedException {
    
      }     //获取一个许可
public void acquire(int permits) throws InterruptedException {
    
     }    //获取permits个许可
public void release() {
    
     }          //释放一个许可
public void release(int permits) {
    
     }    //释放permits个许可

acquire() is used to acquire a license, if no license can be obtained, it will wait until the license is obtained.

release() is used to release the license. Note, before releasing the license, make sure to get the license first. Otherwise, the total number of licenses will be wrong

If you want to get the execution result immediately, you can use the following methods:

public boolean tryAcquire() {
    
     };    //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
    
     };  //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
public boolean tryAcquire(int permits) {
    
     }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException {
    
     }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
public int availablePermits();  // 返回此信号量中可用的许可证的当前数量。

code practice

SemaphoreSpecific usage through examples :

There are five parking spaces in the parking lot, and ten cars need to enter the parking lot to park. At this time, it is necessary to ensure that only five cars can enter when the parking lot is the largest, and only one car can enter when one goes out.

Code:

 public static void main(String[] args) {
    
    
        // 停车场车位数量
        Semaphore semaphore = new Semaphore(5);

        for (int i = 1; i <= 10; i++) {
    
    
            Thread thread = new Thread(() -> {
    
    
                try {
    
    
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "进入停车场");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                    System.out.println(Thread.currentThread().getName() + "驶离停车场");
                } catch (InterruptedException e) {
    
    
                    throw new RuntimeException(e);
                }finally {
    
    
                    semaphore.release();
                }
            }, i + "号车");
            thread.start();
        }
    }

operation result:

1号车进入停车场
4号车进入停车场
3号车进入停车场
2号车进入停车场
5号车进入停车场
1号车驶离停车场
7号车进入停车场
4号车驶离停车场
6号车进入停车场
5号车驶离停车场
8号车进入停车场
3号车驶离停车场
9号车进入停车场
9号车驶离停车场
10号车进入停车场
2号车驶离停车场
6号车驶离停车场
7号车驶离停车场
8号车驶离停车场
10号车驶离停车场

Process finished with exit code 0

SemaphoreIn fact, it is somewhat similar to a lock. It is generally used to control access to a certain set of resources.

Guess you like

Origin blog.csdn.net/weixin_43847283/article/details/128517491