一个例子
public class Demo1 {
private static final Lock lock = new ReentrantLock();// 默认非公平
public static void main(String[] args) {
new Thread(()-> {
test();
},"test-1").start();
new Thread(()-> {
test();
},"test-2").start();
}
static void test() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "获得锁");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + "释放锁");
}
}
}
2. 调用时序图
3. lock.lock()代码分析
- ReentrantLock.java
public void lock() {
// 这里是获取锁的入口
sync.lock();
}
- NonfairSync 是ReentrantLock的内部类
final void lock() {
// cas尝试能不能获取到锁,获取成功之后设置state为1
if (compareAndSetState(0, 1))
// 成功获取之后设置锁的owner是当前线程
setExclusiveOwnerThread(Thread.currentThread());
else
// 没有获取到锁去排队
acquire(1);
}
- AbstractQueuedSynchronizer.java
// cas操作尝试获取锁
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
- AbstractQueuedSynchronizer.java
// 竞争锁失败去排队
public final void acquire(int arg) {
// 先尝试一下获取锁,获取锁失败之后走&&后面的逻辑;公平锁和非公平锁的tryAcquire实现不同
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();// 如果线程在被挂起的过程中被外部中断了,被唤醒之后响应中断的操作
}
- NonfairSync.java
// 非公平锁中的实现
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);// 走默认实现
}
- Sync.java
//非公平尝试获得锁
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();//获取一下当前锁的状态,万一持有锁的线程已经释放了呢
if (c == 0) {
if (compareAndSetState(0, acquires)) {//cas一下,尝试获得锁
setExclusiveOwnerThread(current);//成功,设置锁的owner是自己
return true;
}
}
// 如果锁已经被持有,看一下是不是自己
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires; //重入次数增加
if (nextc < 0) // overflow ??为什么会出现负值
throw new Error("Maximum lock count exceeded");
setState(nextc); // 设置state
return true;
}
return false; //获得锁失败
}
- AbstractQueuedSynchronizer.java
// 把每获得锁的线程封装为一个节点 mode此时=null
private Node addWaiter(Node mode) {
// 生成一个节点,next为null
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;
// 这里cas操作是为了原子性操作去设置tail
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
// 生成wait队列的实现
enq(node);
// node总是被插入到最后,返回自己
return node;
}
- AbstractQueuedSynchronizer.java
// 生成一个链
private Node enq(final Node node) {
// 自旋生成链表
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
// 这里会存在并发,当前线程如果设置head失败,说明有其他线程在设置,自旋操作后会走到else分支
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
// 这里会存在并发,设置当前节点为尾节点,如果设置失败,说明其他线程在设置,自旋后重新尝试设置
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
- AbstractQueuedSynchronizer.java
// 把当前线程挂起,设置前一个节点的waitStatus=-1
// node是封装的当前线程的节点
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
// head的下一个节点总是被限唤醒,因此被唤醒的线程继续cas时,p是head节点
if (p == head && tryAcquire(arg)) { // unlock之后才走这里,lock时不走这
//tryAcquire此时还是会去和新线程竞争,如果没获取到,执行下面的逻辑继续等待
setHead(node);// 把自己设置成head节点
p.next = null; // help GC
failed = false;
return interrupted;
}
// shouldParkAfterFailedAcquire判断是否要挂起当前线程
// parkAndCheckInterrupt 挂起当前线程
// 这两个方法执行完之后,线程被挂起,不再继续执行,线程被唤醒之后从这往下继续执行
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
- AbstractQueuedSynchronizer.java
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);// 这里执行完之后,线程就会被挂起,不再继续往下执行
// 复位并返回中当前断状态;当前有可能被外部线程中断,但是自己此时是无法响应的,需要先保存一下中断状态
return Thread.interrupted();
}
至此,获取不到锁的线程会形成一条链表。
4. lock.unlock()代码分析
- ReentrantLock
public void unlock() {
// 释放锁的入口
sync.release(1);
}
- AbstractQueuedSynchronizer
public final boolean release(int arg) {
if (tryRelease(arg)) { // 尝试释放锁,释放成功(state=0)才继续往下执行
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
- Sync
protected final boolean tryRelease(int releases) {
int c = getState() - releases; // 执行一次unlock就减1
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null); // 释放成功,设置锁的owner为空
}
setState(c);
return free; //多次获取锁,没有释放完返回false
}
- AbstractQueuedSynchronizer
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); //把这个线程唤醒去继续执行
}