9.Semaphore介绍和源码分析

并发编程(1)-java中的6中线程状态
并发编程(2)-怎么中断线程?
并发编程(3)-synchronized的实现原理
并发编程(4)-深入理解volatile关键字
并发编程(5)-ReentrantLock源码分析
并发编程(6)-Condition源码分析
并发编程(7)-juc阻塞队列介绍
并发编程(8)-什么是异步责任链

一、Semaphore介绍和使用

信号灯.限流器,限制资源的访问.
本质上: 抢占一个令牌. -> 如果抢占到令牌,就通行, 否则,就阻塞!
acquire() 抢占一个令牌
release() 释放一个令牌.

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(()->{

                try {
                    semaphore.acquire();
                    System.out.println("当前执行的线程:"+ Thread.currentThread().getName());
                    Thread.sleep(1000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
            thread.start();
        }

    }
}


二、源码分析

acquire()

 public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

  public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        // 如果已经没有令牌,将去挂起当前线程
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }


  private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        // aqs队列中添加共享节点
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                   // 尝试获取共享锁
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                 // 挂起当前线程
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }


   final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
               // 获取已经有的令牌
                int available = getState();
                // 剩余的令牌
                int remaining = available - acquires;
                if (remaining < 0 ||
                    // 更新剩余的令牌数
                    compareAndSetState(available, remaining))
                    return remaining;
            }
        }

release()


   public final boolean releaseShared(int arg) {
        // 释放令牌
        if (tryReleaseShared(arg)) {
            // 去唤醒其他aqs中挂起的共享节点
            doReleaseShared();
            return true;
        }
        return false;
    }


   protected final boolean tryReleaseShared(int releases) {
            for (;;) {
                int current = getState();
                // 将令牌数加回去,再通过aqs替换
                int next = current + releases;
                if (next < current) // overflow
                    throw new Error("Maximum permit count exceeded");
                if (compareAndSetState(current, next))
                    return true;
            }
        }


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))
                        continue;            // loop to recheck cases
                     // 轮询将aqs 中的 节点唤醒   
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值