标签:初始 次数 success ready failure should tor public exce
? 锁使用
final Lock lock = new ReentrantLock();
new Thread(()->{
lock.lock();
try {
System.out.println("--------------------");
Thread.sleep(10000L);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
? 公平锁:
final void lock() {
acquire(1);
}
? 非公平锁:
final void lock() {
//尝试获取锁,如果成功就可以获取到
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
//CAS失败,调用acquire进行获取
acquire(1);
}
? 公平锁中没有直接进行CAS获取锁的流程,为了保证公平,而非公平会直接进行一次尝试。
? 非公平是作用于新入的节点,而已经调用过addWaiter方法的节点,则需要排队。
? 两种锁,后面都会调用该方法,主要就是进行获取锁的尝试,如果获取到就退出,如果没有获取到,则需要将当前线程加入到队列中,知道获取到。
public final void acquire(int arg) {
if (!tryAcquire(arg) && //进入1.2.2
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
? 公平锁和非公平锁的区别是:hasQueuedPredecessors() ,该方法主要是判定是否有线程等待的时长大于当前判断线程。
? 公平锁:
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
//锁的状态标记,0则是没有进行锁定,>0,则被锁,state值为锁定次数
int c = getState();
//0代表没有被锁定,开始尝试获取
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//当前锁正在进行重入
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
? 非公平锁:
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
? 其中state是volatile修饰,保证可见,是线程安全的。
如果上述获取锁失败,则需要将当前线程加入到队列之中。
? (1):如果队列不为空,则直接加入到队列末尾;
? (2):如果队列为空或者第一步添加失败,则重复进行添加;
? ReentranLock中多次运用该思想,先尝试进行,如果没有成功则循环重复进行。
private Node addWaiter(Node mode) {
//创建一个Node,mode分为共享和排他
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
//对应于第一步,直接进行一次尝试添加
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//第一次尝试添加失败,则循环添加
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
//队列为空,则构建一个空节点,并将自身添加到后面
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
final boolean acquireQueued(final Node node, int arg) {
//标识是否出现异常,出现异常会进入finally,取消获取
boolean failed = true;
try {
//标识线程在等待唤醒期间是否被打断
boolean interrupted = false;
//循环获取,直到获取到或者出现异常
for (;;) {
//当前线程的pre节点
final Node p = node.predecessor();
//如果当前线程可以获取锁,并且获取成功
if (p == head && tryAcquire(arg)) {
//当前节点设置为head
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//如果节点没有获取到锁,进行判断是否需要进行park
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
? 先进入:shouldParkAfterFailedAcquire(p, node)
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don‘t park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
上述如果返回的true,则标识当前线程进行park:
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
? 以上为进行加锁的全流程,如果线程添加到队列中或者进入park,如果被唤醒或者开始获取到锁的,那么需要分析持有锁的线程在进行释放的时候做了哪些事情。
public final boolean release(int arg) {
//进行一次锁的释放
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
//唤醒下一个节点的线程
unparkSuccessor(h);
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
//退出一次,则将state减少一次
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//c=0,标识持有锁的线程已经释放完,并把锁的当前线程置为null
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}
? 可以看出唤醒的是当前节点后面的节点。
标签:初始 次数 success ready failure should tor public exce
原文地址:https://www.cnblogs.com/mayang2465/p/14621269.html