ReentrantLock重入锁 ,Condition 线程协作类学习
首先我们从源码中可以获知,ReentrantLock是一个同步器的实现,它具有同步器的一些特性,下面我们就讨论下eentrantLock重入锁 ,Condition 线程协作的协同工作。
话不多说,看以下代码
/**
*
*/
package com.cai.Thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*@title:
*@author:allencai
*@date:2018-4-21上午9:57:35
*/
public class SignalThread {
/**
*@method:main
*@descript:TODO
*@author:allencai
*@return:void
*@date:2018-4-21上午9:57:35
*/
//创建重入锁
final static ReentrantLock reentrantLocklock=new ReentrantLock();
//static Condition newCondition;
public static void main(String[] args) {
Condition newCondition = reentrantLocklock.newCondition();
AccessThread accessThread=new AccessThread(newCondition);
accessThread.start();
SendThread sendThread = new SendThread(newCondition);
sendThread.start();
}
static class AccessThread extends Thread{
Condition newCondition;
public AccessThread(Condition newCondition){
this.newCondition=newCondition;
}
@Override
public void run() {
reentrantLocklock.lock();
try {
System.err.println("我要等待接受信号"+this);
newCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("拿到一个信号"+this);
reentrantLocklock.unlock();
}
}
static class SendThread extends Thread{
Condition newCondition;
public SendThread(Condition newCondition){
this.newCondition=newCondition;
}
@Override
public void run() {
reentrantLocklock.lock();
try {
System.err.println("我要发送接受信号"+this);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newCondition.signalAll();
System.err.println("发送一个信号"+this);
reentrantLocklock.unlock();
}
}
}
那我们就讨论下上述代码的实现原理:首先AccessThread 接受信号线程启动获取重入锁,获取执行权,然后输出我们的语句“等待信号”,当调用await方法时,封装我们的线程信息,同时将我们线程从AQS队列中移除,同时将其加入到condition队列,释放锁,此时循环AQS队列中线程,因为我们AQS队列只有SendThread线程,所以它获取到我们的锁,然后产生信号,休眠1秒钟,唤醒其他线程此时我们线程AccessThread从condition队列中加入到AQS队列中,当我们unlock时释放锁,我们AccessThread重新获得锁执行线程任务。详解如下:
首先还是要明白,reentrantLock.newCondition()
返回的是Condition
的一个实现,该类在AbstractQueuedSynchronizer
中被实现,叫做newCondition()
1 |
public Condition newCondition() { return sync.newCondition(); }
|
它可以访问AbstractQueuedSynchronizer
中的方法和其余内部类(AbstractQueuedSynchronizer
是个抽象类,至于他怎么能访问,这里有个很奇妙的点,后面我专门用demo说明 )
现在,我们一起来看下Condition
类的实现,还是从上面的demo入手,
为了方便书写,我将AbstractQueuedSynchronizer
缩写为AQS
当await
被调用时,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter(); // 将当前线程包装下后,
// 添加到Condition自己维护的一个链表中。
int savedState = fullyRelease(node); // 释放当前线程占有的锁,从demo中看到,
// 调用await前,当前线程是占有锁的
int interruptMode = 0 ;
while (!isOnSyncQueue(node)) { // 释放完毕后,遍历AQS的队列,看当前节点是否在队列中,
// 不在 说明它还没有竞争锁的资格,所以继续将自己沉睡。
// 直到它被加入到队列中,聪明的你可能猜到了,
// 没有错,在singal的时候加入不就可以了?
LockSupport.park( this );
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0 )
break ;
}
// 被唤醒后,重新开始正式竞争锁,同样,如果竞争不到还是会将自己沉睡,等待唤醒重新开始竞争。
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null )
unlinkCancelledWaiters();
if (interruptMode != 0 )
reportInterruptAfterWait(interruptMode);
} |
回到上面的demo,锁被释放后,线程1开始沉睡,这个时候线程因为线程1沉睡时,会唤醒AQS队列中的头结点,所所以线程2会开始竞争锁,并获取到,等待3秒后,线程2会调用signal方法,“发出”signal信号,signal方法如下:
1
2
3
4
5
6
7
8
|
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter; // firstWaiter为condition自己维护的一个链表的头结点,
// 取出第一个节点后开始唤醒操作
if (first != null )
doSignal(first);
} |
说明下,其实Condition
内部维护了等待队列的头结点和尾节点,该队列的作用是存放等待signal信号的线程,该线程被封装为Node
节点后存放于此。
1
2
3
4
5
6
|
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** First node of condition queue. */
private transient Node firstWaiter;
/** Last node of condition queue. */
private transient Node lastWaiter;
|
关键的就在于此,我们知道AQS自己维护的队列是当前等待资源的队列,AQS会在资源被释放后,依次唤醒队列中从前到后的所有节点,使他们对应的线程恢复执行。直到队列为空。
而Condition自己也维护了一个队列,该队列的作用是维护一个等待signal信号的队列,两个队列的作用是不同,事实上,每个线程也仅仅会同时存在以上两个队列中的一个,流程是这样的:
- 线程1调用
reentrantLock.lock
时,线程被加入到AQS的等待队列中。 - 线程1调用
await
方法被调用时,该线程从AQS中移除,对应操作是锁的释放。 - 接着马上被加入到
Condition
的等待队列中,以为着该线程需要signal
信号。 - 线程2,因为线程1释放锁的关系,被唤醒,并判断可以获取锁,于是线程2获取锁,并被加入到AQS的等待队列中。
- 线程2调用
signal
方法,这个时候Condition
的等待队列中只有线程1一个节点,于是它被取出来,并被加入到AQS的等待队列中。 注意,这个时候,线程1 并没有被唤醒。 -
signal
方法执行完毕,线程2调用reentrantLock.unLock()
方法,释放锁。这个时候因为AQS中只有线程1,于是,AQS释放锁后按从头到尾的顺序唤醒线程时,线程1被唤醒,于是线程1回复执行。 - 直到释放所整个过程执行完毕。
可以看到,整个协作过程是靠结点在AQS的等待队列和Condition
的等待队列中来回移动实现的,Condition
作为一个条件类,很好的自己维护了一个等待信号的队列,并在适时的时候将结点加入到AQS的等待队列中来实现的唤醒操作。
看到这里,signal方法的代码应该不难理解了。
取出头结点,然后doSignal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public final void signal() {
if (!isHeldExclusively()) {
throw new IllegalMonitorStateException();
}
Node first = firstWaiter;
if (first != null ) {
doSignal(first);
}
} private void doSignal(Node first) {
do {
if ((firstWaiter = first.nextWaiter) == null ) // 修改头结点,完成旧头结点的移出工作
lastWaiter = null ;
first.nextWaiter = null ;
} while (!transferForSignal(first) && // 将老的头结点,加入到AQS的等待队列中
(first = firstWaiter) != null );
} final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* Splice onto queue and try to set waitStatus of predecessor to
* indicate that thread is (probably) waiting. If cancelled or attempt
* to set waitStatus fails, wake up to resync (in which case the
* waitStatus can be transiently and harmlessly wrong).
*/
Node p = enq(node);
int ws = p.waitStatus;
// 如果该结点的状态为cancel 或者修改waitStatus失败,则直接唤醒。
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true ;
} |
可以看到,正常情况 ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)
这个判断是不会为true
的,所以,不会在这个时候唤醒该线程。
只有到发送signal
信号的线程调用reentrantLock.unlock()
后因为它已经被加到AQS的等待队列中,所以才会被唤醒。