Semaphore 唤醒失败问题

    static Semaphore  semaphore = new Semaphore(5);
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 3, 1,
                TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5),
                new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i < 50; i++) {
            executor.submit(new Task());
        }
        try {
            Thread.sleep(50000);
            executor.shutdownNow();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static class  Task implements Runnable{
        @Override
        public void run() {
            if (semaphore.tryAcquire()) {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+":get");
                    Thread.sleep(2000);
                    semaphore.release();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

当   tryAcquire 和 acquire 同时出现时,需要执行两次release方法

因为 tryAcquire 和 acquire 方法都会执行一次尝试CAS(1)的方法    导致同时消耗两个信号  若只执行一次release方法会造成信号量回填速度跟不上消耗速度导致所有参与当前   semaphore 的线程全部阻塞。

tryAcquire()-->  sync.nonfairTryAcquireShared(1) >= 0;      

  final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))   //直接子类cas
            }
   }
出现一次cas消耗信号量操作

acquire()-->     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 {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);    //回调子类 cas
                    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);
        }
    }

两者都会操作 cas 用来消耗信号量

因此当需要获取permit信号量时,二者等价    只需要选用其中一个即可

二者的差别:

tryAcquire返回的是一个bool 可直接用作判断是否成功
acquire执行了一个可中断方法,可能出现中断异常

如有理解错误,请斧正

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值