1.原理
1.互斥变量标志锁对象的状态
private volatile int state
2.双向链表存储等待的线程
3.没有抢到锁的线程阻塞,抢到锁的线程执行
当抢到锁的线程执行完后唤醒链表head指向的线程
阻塞和唤醒使用的是LockSupport类的park方法和unpark方法
2.两个线程AThread、BThread抢占锁资源Demo
package com.yinzhen.demo.aqs;
import java.util.concurrent.locks.ReentrantLock;
public class DemoAQSThread extends Thread{
//非公平锁
private static ReentrantLock reentrantLock = new ReentrantLock();
public static void main(String[] args) {
DemoAQSThread threadA = new DemoAQSThread();
threadA.setName("ThreadA");
threadA.start();
DemoAQSThread threadB = new DemoAQSThread();
threadB.setName("ThreadB");
threadB.start();
}
@Override
public void run() {
try {
reentrantLock.lock();
long startTime = System.currentTimeMillis();
System.out.println("hello---"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+"线程执行花费:"+(System.currentTimeMillis()-startTime));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
}
3.demo分析源码
1.ThreadA和ThreadB同时执行reentrantLock.lock();
2.默认锁资源的状态state是0,ThreadA和ThreadB都使用CAS算法把0设置为1,谁设置成功谁获取到锁
final void lock() {
//默认锁资源的状态state是0,ThreadA和ThreadB都使用CAS算法把0设置为1,谁设置成功谁获取到锁
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
3.假设ThreadA获取了锁,把自己设置成占有锁的线程
开始执行ThreadA的代码
4.ThreadB没有获取到锁资源
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
4.1尝试获取锁,肯定是获取不到的
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;
}
4.2把自己放到阻塞队列中
private Node addWaiter(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 {
//把线程B节点前驱指向Head节点,线程B节点设置为Tail节点
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
4.3把自己阻塞
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
//如果node的前驱是head节点,并且获取到了锁
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//锁获取失败
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//把自己的前驱的等待状态设置为SIGNAL
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;
}
//调用LockSupport.park(this)把自己阻塞
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
5.当线程A执行完后执行reentrantLock.unlock();方法唤醒head的下一个线程
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)‘
//h.waitStatus != 0 表示后面又线程需要唤醒应该是-1状态Node.SIGNAL
// static final int SIGNAL = -1;
//从头节点开始唤醒下一个线程
unparkSuccessor(h);
return true;
}
return false;
}
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
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);
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
//状态减releases
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
//status为0表示无锁状态
free = true;
//把占有锁的线程设置为空
setExclusiveOwnerThread(null);
}
setState(c);
//释放成功失败
return free;
}