protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
//加锁的方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
//如果当前线程是被中断的,则抛出异常
if (Thread.interrupted())
throw new InterruptedException();
//尝试获取锁,返回剩余共享锁的数量 如果大于等于0,则表示锁获取成功,如果小于0,则获
取失败
if (tryAcquireShared(arg) < 0)//该方法被公平锁和非公平锁重写
//可获取的锁的数量 小于0则将当前线程加入等待队列挂起,自旋
doAcquireSharedInterruptibly(arg);//AQS自己的方法
}
//加锁方法
//返回负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
protected int tryAcquireShared(int arg) {//被子类公平锁和非公平锁重写
throw new UnsupportedOperationException();
}
//释放锁
public final boolean releaseShared(int arg) {
//自旋直到释放锁成功
if (tryReleaseShared(arg)) {//该方法被Sync重写
//如果释放成功,则调用下面的方法来唤醒AQS队列中等待的线程
doReleaseShared();//AQS自己的方法
return true;
}
return false;
}
//释放锁
//arg为释放锁的次数,尝试释放资源,如果释放后允许唤醒后续等待结点返回True,否则返回
False
protected boolean tryReleaseShared(int arg) {//被Sync锁重写了,公平锁和非公平锁
共用
throw new UnsupportedOperationException();
}
private void doAcquireSharedInterruptibly(int arg) throws InterruptedException {
//加入等待队列的尾部 将当前线程封装为一个Node
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {//死循环去获取共享锁(可以同时被多个线程获取)
//获取当前节点的上一个节点
final Node p = node.predecessor();
评论0