Semaphore类

2021-09-24  本文已影响0人  七喜丶

基本概念

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly
Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource

计数信号量。从概念上讲,信号量保持一套许可证。如果需要,每个acquire()块都会阻止,直到有许可证可用,然后获取它。每个release()都添加了一个许可证,可能会发布阻止性获取者。但是,不使用实际允许的对象;信号量只是保持可用数字的计数并相应地起作用
信号量通常用于限制访问某些(物理或逻辑)资源的线程数量

初始值为1的信号量——二进制信号量

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery

初始化为 1 的信号量,并且使用时最多只有一个许可可用,可以用作互斥锁。这通常被称为二进制信号量,因为它只有两种状态:一种许可可用,或零许可可用。当以这种方式使用时,二进制信号量具有属性(与许多Lock 实现不同),即“锁”可以由所有者以外的线程释放(因为信号量没有所有权的概念)。这在某些特定上下文中很有用,例如死锁恢复

公平参数(a fairness parameter)

The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. In particular, barging is permitted, that is, a thread invoking acquire() can be allocated a permit ahead of a thread that has been waiting - logically the new thread places itself at the head of the queue of waiting threads. When fairness is set true, the semaphore guarantees that threads invoking any of the acquire methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO). Note that FIFO ordering necessarily applies to specific internal points of execution within these methods. So, it is possible for one thread to invoke acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed tryAcquire methods do not honor the fairness setting, but will take any permits that are available

此类的构造函数可以选择接受 公平参数。当设置为 false 时,此类不保证线程获取许可的顺序。特别是,闯入是允许的,也就是说,一个线程调用acquire()可以提前已经等待线程分配的许可证-在逻辑上新的线程将自己置于等待线程队列的头部。当公平设置为真时,信号量保证线程调用任何acquire选择方法以按照处理它们调用这些方法的顺序(先进先出;FIFO)获得许可。请注意,FIFO 排序必然适用于这些方法中的特定内部执行点。因此,一个线程可能在另一个线程acquire之前调用,但在另一个线程 之后到达排序点,从方法返回时也是如此。另请注意,不计时tryAcquire方法不遵守公平设置,但会采用任何可用的许可

了解下图方法详解请点击 🔜 详情

代码案例

高速收费站场景

package com.itheima.mysemaphore;

import java.util.concurrent.Semaphore;

public class MyRunnable implements Runnable {
    //1.获得管理员对象,
    private Semaphore semaphore = new Semaphore(2);
    @Override
    public void run() {        
        try {
            //2.获得通行证
            semaphore.acquire();
            //3.开始行驶
            System.out.println("获得了通行证开始行驶");
            Thread.sleep(2000);
            System.out.println("归还通行证");
            //4.归还通行证
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package com.itheima.mysemaphore;

public class MySemaphoreDemo {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();

        for (int i = 0; i < 100; i++) {
            new Thread(mr).start();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读