目录
I.初始化状态
II.await()操作
III.signal()操作
Condition的数据结构
线程何时阻塞和释放
await()方法
signal()和signalAll()方法
JUC提供了Lock可以方便的进行锁操作,但是有时候我们也需要对线程进行条件性的阻塞和唤醒,这时我们就需要condition条件变量,它就像是在线程上加了多个开关,可以方便的对持有锁的线程进行阻塞和唤醒。
Condition的概念
大体实现流程
3个主要方法
Condition的数据结构
线程何时阻塞和释放
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 {
// 1.如果当前线程被中断,则抛出中断异常 if (Thread.interrupted()) throw new InterruptedException(); // 2.将节点加入到Condition队列中去,这里如果lastWaiter是cancel状态,那么会把它踢出Condition队列。 Node node = addConditionWaiter(); // 3.调用tryRelease,释放当前线程的锁 long savedState = fullyRelease(node); int interruptMode = 0; // 4.为什么会有在AQS的等待队列的判断? // 解答:signal操作会将Node从Condition队列中拿出并且放入到等待队列中去,在不在AQS等待队列就看signal是否执行了 // 如果不在AQS等待队列中,就park当前线程,如果在,就退出循环,这个时候如果被中断,那么就退出循环 while (!isOnSyncQueue(node)) { LockSupport.park(this); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } // 5.这个时候线程已经被signal()或者signalAll()操作给唤醒了,退出了4中的while循环 // 自旋等待尝试再次获取锁,调用acquireQueued方法 if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); } |
signal和signalAll方法
await*()清楚了,现在再来看signal/signalAll就容易多了。按照signal/signalAll的需求,就是要将Condition.await*()中FIFO队列中第一个Node唤醒(或者全部Node)唤醒。尽管所有Node可能都被唤醒,但是要知道的是仍然只有一个线程能够拿到锁,其它没有拿到锁的线程仍然需要自旋等待,就上上面提到的第4步(acquireQueued)。
1
2 3 4 5 6 7 |
public final void signal() {
if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignal(first); } |
这里先判断当前线程是否持有锁,如果没有持有,则抛出异常,然后判断整个condition队列是否为空,不为空则调用doSignal方法来唤醒线程,看看doSignal方法都干了一些什么:
1
2 3 4 5 6 7 8 |
private void doSignal(Node first) {
do { if ( (firstWaiter = first.nextWaiter) == null) lastWaiter = null; first.nextWaiter = null; } while (!transferForSignal(first) && (first = firstWaiter) != null); } |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
final boolean transferForSignal(Node node) {
/* * 设置node的waitStatus:Condition->0 */ if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) return false; /* * 加入到AQS的等待队列,让节点继续获取锁 * 设置前置节点状态为SIGNAL */ Node p = enq(node); int c = p.waitStatus; if (c > 0 || !compareAndSetWaitStatus(p, c, Node.SIGNAL)) LockSupport.unpark(node.thread); return true; } |
1
2 3 4 5 6 7 8 9 |
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null; do { Node next = first.nextWaiter; first.nextWaiter = null; transferForSignal(first); first = next; } while (first != null); } |
这个方法就相当于把Condition队列中的所有Node全部取出插入到等待队列中去。
Condition应用示例:生产者和消费者
Condition
实例实质上被绑定到一个锁上。要为特定 Lock
实例获得
Condition
实例,请使用其 newCondition()
方法。在最后我们来看一个应用示例
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
/**
* 生产者、消费者示例 */ public class ConditionTest { private int storage; private int putCounter; private int getCounter; private Lock lock = new ReentrantLock(); private Condition putCondition = lock.newCondition(); private Condition getCondition = lock.newCondition(); public void put() throws InterruptedException { try { lock.lock(); if (storage > 0) { putCondition.await(); } storage++; System.out.println("put => " + ++putCounter ); getCondition.signal(); } finally { lock.unlock(); } } public void get() throws InterruptedException { try { lock.lock(); lock.lock(); if (storage <= 0) { getCondition.await(); } storage--; System.out.println("get => " + ++getCounter); putCondition.signal(); } finally { lock.unlock(); lock.unlock(); } } public class PutThread extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { try { put(); } catch (InterruptedException e) { } } } } public class GetThread extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { try { get(); } catch (InterruptedException e) { } } } } public static void main(String[] args) { final ConditionTest test = new ConditionTest(); Thread put = test.new PutThread(); Thread get = test.new GetThread(); put.start(); get.start(); } |