先看构造方法,这是一个非公平锁
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
锁