Semaphore笔记

先看构造方法,这是一个非公平锁
public Semaphore( int permits) {
//这个值就是state
sync = new NonfairSync(permits);
}

然后看开始调用了
semaphore .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);
}
//进入这里

final int nonfairTryAcquireShared( int acquires) {
for (;;) {
//这个是之前设置的初始值,后面会修改
int available = getState();
int remaining = available - acquires;
//判断是否获得锁,小于0就是用光了可用线程
if (remaining < 0 ||
//这边修改state,失败继续自旋
compareAndSetState(available, remaining))
return remaining;
}
}

然后返回 acquireSharedInterruptibly方法

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

接着进入 acquireSharedInterruptibly方法看看,这个就是锁里面的方法,这里就不说了

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);
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);
}
}

再看看semaphore .release()释放
进入

public void release() {
sync .releaseShared( 1 );
}

最后进入这里

protected final boolean tryReleaseShared( int releases) {
for (;;) {
int current = getState();
//往state上加值
int next = current + releases;
if (next < current) // overflow
throw new Error( "Maximum permit count exceeded" );
//自旋修改
if (compareAndSetState(current, next))
return true ;
}
}

总结一下 Semaphore信号量就是一个把state改变了的 Reentrant

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值