Semaphore底层原理

Java并发编程:Semaphore详解与应用实例
本文深入解析了Java并发工具Semaphore的使用,通过一个网吧抢座的示例展示了其控制并发数的功能。Semaphore在加锁过程中涉及tryAcquireShared、doAcquireSharedInterruptibly等方法,详细阐述了获取和释放锁的内部机制,包括线程的等待与唤醒过程。
一、SemaphoreDemo

Semaphore的应用场景就是加锁异步控制并发数

下面demo可以理解为抢夺共享资源

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) {
        String[] name = {"小胖", "大花", "大肥", "小桌子", "小椅子"};
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 5; i++) {
            //五个人去争夺三个共享资源
            //五个人一放学就去网吧抢机子,网吧只有三台电脑
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + "进入网吧");
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "抢到了电脑");
                        Thread.sleep(5000);
                        System.out.println(Thread.currentThread().getName() + "下机了");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                }
            }, name[i]).start();
        }
    }
}

运行结果

抢不到电脑的要等别人下机之后才能上网

在这里插入图片描述


二、加锁

在调用semaphore.acquire()方法后,进入InterruptedException(),然后点击进入tryAcquireShared()

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }

从tryAcquireShared()进入nonfairTryAcquireShared()

拿到state值后进行减一操作,然后CAS修改state值后返回

final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))
                    return remaining;
            }
        }

如果state值小于0进入doAcquireSharedInterruptibly()

1)addWaiter(Node.SHARED)方法将当前线程加入同步队列,是一个双向链表,如果初始化为空,则进入enq();

2)enq()方法中:new Node()作为head,指向当前线程结点作为tail;

3)如果prev为head则进入tryAcquireShared(),然后尝试CAS修改state

4)将waitStatus设置为-1并且LockSupport.unpark()阻塞线程

private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor(); // 1)如果prev为head则进入tryAcquireShared()
                if (p == head) {
                    int r = tryAcquireShared(arg); // 3)尝试CAS修改state
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);  
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&  //4)将waitStatus设置为-1并且LockSupport.unpark()阻塞线程
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

for(;)循环尝试修改state,成功后进入setHeadAndPropagate()

设置当前node为head,如果当前waitStauts为-1,则判断下一结点是否为null或者new Node(),如果是则直接唤醒

private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // Record old head for check below
        setHead(node);
        /*
         * Try to signal next queued node if:
         *   Propagation was indicated by caller,
         *     or was recorded (as h.waitStatus either before
         *     or after setHead) by a previous operation
         *     (note: this uses sign-check of waitStatus because
         *      PROPAGATE status may transition to SIGNAL.)
         * and
         *   The next node is waiting in shared mode,
         *     or we don't know, because it appears null
         *
         * The conservatism in both of these checks may cause
         * unnecessary wake-ups, but only when there are multiple
         * racing acquires/releases, so most need signals now or soon
         * anyway.
         */
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }

三、释放锁

进入releaseShared()

public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

tryReleaseShared()

释放锁,将state值加一,CAS修改成功后返回true

protected final boolean tryReleaseShared(int releases) {
            for (;;) {
                int current = getState();
                int next = current + releases;
                if (next < current) // overflow
                    throw new Error("Maximum permit count exceeded");
                if (compareAndSetState(current, next))
                    return true;
            }
        }

tryReleaseShared()返回true后进入doReleaseShared()

for(;;)循环判断head头结点不会null也不会尾结点,如果waitStatus为-1,则先CAS修改waitStatus为0,然后唤醒下一结点

private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) // CAS自旋修改waitStatus为0
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }


如果CAS自旋修改waitStatus=0成功,进入unparkSuccessor()

保障判断waitStatus是否为0,判断下一结点是否为空,不为空则唤醒下一结点。

private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread); // 唤醒线程
    }
<think>我们被要求回答关于Semaphore(信号量)的概念、原理和应用场景。根据用户提供的引用和之前的对话历史(关于CyclicBarrier),我们需要组织一个结构化的回答。 概念:SemaphoreJava并发包中的一个同步工具,用于控制对共享资源的并发访问数量,通过许可证(permits)机制实现。 原理:基于AQS(AbstractQueuedSynchronizer)实现,有公平模式和非公平模式。 应用场景:资源池管理(如数据库连接池)、限流控制、生产者-消费者模型等。 注意:用户提供的引用[1][2][3][4][5]都是关于Semaphore的,我们可以引用这些内容。 回答结构: 1. 核心概念 2. 实现原理(包括AQS的底层实现,公平与非公平模式) 3. 典型应用场景(结合代码示例) 4. 与CountDownLatch的对比(可选,因为之前对比了CyclicBarrier和CountDownLatch,这里可以提一下Semaphore的特点) 5. 生成相关问题 根据要求,我们需要使用LaTeX格式的行内数学表达式(用$...$)和独立公式(用$$...$$)。但是,在信号量的描述中,数学表达式可能不多,主要涉及计数器的操作(如P操作和V操作)。 另外,在回答中引用段落末尾自然地添加引用标识,例如[^1]。 我们开始组织回答。</think>### Semaphore(信号量)详解 #### 一、核心概念 SemaphoreJava 并发包(`java.util.concurrent`)中的同步工具,用于**控制对共享资源的并发访问数量**。其核心模型基于经典的**Dijkstra信号量机制**: 1. **许可证机制** - 维护一个虚拟的许可证计数器(permits) - 线程访问资源前需获取许可证($P$操作:`acquire()`) - 使用后释放许可证($V$操作:`release()`) ```java Semaphore semaphore = new Semaphore(3); // 允许3个线程同时访问 semaphore.acquire(); // 获取许可证(P操作) // 访问共享资源... semaphore.release(); // 释放许可证(V操作) ``` 2. **公平性模式** - **非公平模式(默认)**:允许线程插队获取许可,吞吐量高但可能引发饥饿 - **公平模式**:按 FIFO 顺序分配许可,避免饥饿但性能较低 ```java // 创建公平信号量 Semaphore fairSemaphore = new Semaphore(3, true); ``` 3. **与锁的区别** - 锁(如 `ReentrantLock`)是互斥锁($M=1$ 的信号量特例) - 信号量支持多线程并发访问($M \geq 1$) #### 二、实现原理(基于 AQS) 通过 **AbstractQueuedSynchronizer(AQS)** 实现线程同步[^4]: ```mermaid graph TB A[acquire] --> B{许可证数量>0?} B -->|是| C[许可证-1, 直接访问] B -->|否| D[线程进入CLH队列阻塞] E[release] --> F[许可证+1] F --> G[唤醒队列头线程] ``` 1. **核心源码结构** ```java public class Semaphore { private final Sync sync; // 继承自AQS abstract static class Sync extends AbstractQueuedSynchronizer { Sync(int permits) { setState(permits); } // state存储许可证数 final int nonfairTryAcquireShared(int acquires) { while (true) { int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; // <0时阻塞 } } } } ``` 2. **关键操作** - **acquire()**: $$ \text{state} = \text{state} - 1 \quad \text{if} \quad \text{state} > 0 $$ - **release()**: $$ \text{state} = \text{state} + 1 $$ #### 三、典型应用场景 1. **资源池管理**(如数据库连接池) ```java public class ConnectionPool { private final Semaphore semaphore = new Semaphore(10); // 最大10连接 private final BlockingQueue<Connection> pool = new ArrayBlockingQueue<>(10); public Connection getConnection() throws InterruptedException { semaphore.acquire(); // 获取访问许可 return pool.take(); } public void releaseConnection(Connection conn) { pool.add(conn); semaphore.release(); // 释放许可 } } ``` 2. **限流控制**(API 请求限流) ```java Semaphore rateLimiter = new Semaphore(100); // 每秒100请求 void handleRequest() { if (rateLimiter.tryAcquire()) { // 非阻塞获取 processRequest(); rateLimiter.release(); } else { rejectRequest(); // 触发限流 } } ``` 3. **生产者-消费者模型**(有界缓冲区) ```java Semaphore emptySlots = new Semaphore(BUFFER_SIZE); // 初始空槽数 Semaphore filledSlots = new Semaphore(0); // 初始满槽数 // 生产者 void produce() { emptySlots.acquire(); // 等待空槽 buffer.add(item); filledSlots.release(); // 增加满槽 } // 消费者 void consume() { filledSlots.acquire(); // 等待满槽 buffer.take(); emptySlots.release(); // 增加空槽 } ``` 4. **并发任务控制** ```java Semaphore taskController = new Semaphore(Runtime.getRuntime().availableProcessors()); void submitTask(Runnable task) { taskController.acquire(); executor.execute(() -> { try { task.run(); } finally { taskController.release(); } }); } ``` #### 四、与 CountDownLatch 对比 | **特性** | Semaphore | CountDownLatch | |------------------|--------------------------------|-------------------------| | 核心功能 | 控制资源访问数量 | 等待事件完成 | | 重置能力 | ✅ 许可证可重复使用 | ❌ 一次性 | | 计数方向 | 可增可减 | 单向递减 | | 阻塞线程 | 资源不足时阻塞 | 调用线程等待计数归零 | | 典型场景 | 连接池/限流 | 启动前依赖检查 | > ⚠️ **注意事项**: > 1. 必须保证 `release()` 在 `finally` 块中调用,避免许可证泄漏 > 2. 公平模式在竞争激烈时性能下降约 30%,需权衡使用[^3] > 3. 支持 `tryAcquire(timeout)` 避免死锁 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值