Semaphore底层原理

一、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); // 唤醒线程
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值