lock锁在源码中是怎么设计的?
1)、首先要有互斥的条件,通过一个volatile修饰的变量来标记锁是否被占用 volatile state (0无锁,1有锁,>1 重入锁)
2)、当线程抢占失败时,要进行等待和唤醒,释放CPU时间片资源
3)、等待队列资源的存储(通过数据结构存储)
4)、可重入特性(通过线程的ThreadId来判读是否为当前线程)
5)、公平非公平(能否插队)
如下一个demo:
private static int count = 0;
static Lock lock = new ReentrantLock();
public static void inc(){
lock.lock();
try{
Thread.sleep(1);
count++;
decr();//重入锁
}catch(InterruptedException e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
public static void decr(){
lock.lock();
try {
Thread.sleep(1);
count--;
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
new Thread(()->inc()).start();
}
Thread.sleep(4000);
System.out.println(count);
}
查看ReentrantLock类图
AQS核心源码分析:
1、共享资源来实现互斥,通过volatile int state 来实现互斥的效果(0为无锁,1为有锁,>1为重入锁)获取锁,NonfairSync非公平锁lock()
lock()
final void lock() {
if (compareAndSetState(0, 1))//乐观锁进行获取(返回true/false),实现,通过判断预期值为0的话去修改state状态为1
setExclusiveOwnerThread(Thread.currentThread());//如果当前state的值为0的话setExclusiveOwnerThread()设置当前独占线程(保存当前线程)
else
acquire(1);
}
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
//该方法为native本地方法底层的设计为根据偏移量的去获取到内存地址位置去进行判断(C里面的操作)
}
private transient Thread exclusiveOwnerThread;
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
对应的流程图为
2、没有获得锁的线程
addWaiter()
public final void acquire(int arg) { //没有获得锁的线程进入acquire(1)
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
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;//第一次时尾结点为null
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))//通过CAS的方式去设置head进行初始化,保证多线程操作的安全性
tail = head;//指针指向同一个对象
} else {//初始化完之后
node.prev = t;//指向当前进来的线程(未获得锁)向前的指向
if (compareAndSetTail(t, node)) {//改变尾部节点的指向(CAS保证安全性)
t.next = node;//改变尾部节点的指向
return t;
}
}
}
}
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)) {//判断前一个节点是否为头节点,如果是进行尝试一次抢占
setHead(node);//若抢占成功则设置当前节点(当前线程)为头节点且设置thread和pref为null
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(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.
*/
//通过CAS去替换waitStatus状态值(前一个节点的状态即头结点设置为signal状态)
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//通过LockSupport.park挂起线程
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//线程运行到这之后意味着线程B、C释放了CPU时间片资源,实现了一个阻塞状态
return Thread.interrupted();
}
流程图:
3、线程A运行完成释放资源
release,在acquireQueued中会进行自旋判断,进行一次tryAcquire之后pack挂起释放CPU时间片资源,自旋判断当线程A释放资源之后进行unpark唤醒,线程B进行tryAcquire
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);//通过unpark进行唤醒
return true;
}
return false;
}
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;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
流程图为: