Introduction to the semaphore Semaphore of the synchronization component of the JUC-AQS framework

Semaphore concept

Semaphore is a counter semaphore, which maintains a permission set to control the consumption and recycling of certain resources. When the thread calls the acquire () method, if the permission is insufficient, the thread will block until a permission is available. The release () method will release a license.

Semaphore

Semaphore provides two construction methods:

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

Let me talk about some of the more important methods in the Semaphore class. The first is the acquire () and release () methods:

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

acquire()Used to obtain a license. If no license can be obtained, it will wait until the license is obtained.

release()Used to release licenses. Note that you must obtain permission before releasing the license.

These four methods will be blocked. 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

In addition, the number of available licenses can be obtained through the availablePermits () method.

Let's look at the specific use of Semaphore through an example:

If a factory has 5 machines, but there are 8 workers, a machine can only be used by one worker at the same time. Only after it is used up can other workers continue to use it. Then we can achieve it through Semaphore:

package com.bestksl.example.aqs;

import java.util.concurrent.Semaphore;

public class test {
    public static void main(String[] args) {
        int N = 8;            //工人数
        Semaphore semaphore = new Semaphore(5); //机器数目
        for (int i = 0; i < N; i++)
            new Worker(i, semaphore).start();
    }

    
}
// 工人类
class Worker extends Thread {
    private int num;
    private Semaphore semaphore;

    public Worker(int num, Semaphore semaphore) {
        this.num = num;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println("工人" + this.num + "占用一个机器在生产...");
            Thread.sleep(2000);
            System.out.println("工人" + this.num + "释放出机器");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Results of the

工人0占用一个机器在生产...
工人1占用一个机器在生产...
工人2占用一个机器在生产...
工人4占用一个机器在生产...
工人5占用一个机器在生产...
工人0释放出机器
工人2释放出机器
工人3占用一个机器在生产...
工人7占用一个机器在生产...
工人4释放出机器
工人5释放出机器
工人1释放出机器
工人6占用一个机器在生产...
工人3释放出机器
工人7释放出机器
工人6释放出机器
Published 248 original articles · praised 416 · 90,000 views +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/105463950