java并发包之Condition

一、前言

之前在AQS中介绍到其中的Condition队列,而今天本文就介绍与其相关的Condition。Condition是一个多线程间协调通信的工具类,在synchornize中,使用的是wait和notify来实现,而Condition除了实现wait和notify的功能以外,他的好处在于一个lock可以创建多个Condition,可以选择性的通知wait的线程,接下来看下具体的介绍。

二、主要特点

  1. Condition 的前提是Lock,由AQS中newCondition()方法 创建Condition的对象
  2. Condition await方法表示线程从AQS中移除,并释放线程获取的锁,并进入Condition等待队列中等待,等待被signal
  3. Condition signal方法表示唤醒对应Condition等待队列中的线程节点,并加入AQS中,准备去获取锁。

三、流程示意图:

  1. 有三个节点在AQS中,三个线程分别触发了lock的lock方法,三个节点还处于锁的竞争状态,都在AQS队列中,而已经有两个节点在Condition队列中。
  2. 节点1执行Condition.await(),先在Condition队列队尾添加节点,并释放节点1的锁,并把节点1加入到等待队列中,并把lastWaiter更新为节点1
  3. 节点2执行signal(),将节点4移出Codition队列,并将节点4加入AQS队列中等待获取锁资源

四、源码分析

4.1 await()

  public final void await() throws InterruptedException {
            
            if (Thread.interrupted()) throw new InterruptedException();
            //将当前线程包装成NODE,并将其添加到Condition队列中
            Node node = addConditionWaiter();
            //释放当前线程占有的锁资源
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            //遍历AQS队列,判断节点是否在AQS队列中
            //如果不在说明没有获取锁的资格,则继续阻塞,直到被加入到队列中
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
           //如果被唤醒,则重新开始获取资源,
           //如果竞争不到则继续休眠,等待被唤醒
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT; 
            //检测线程是中断唤醒还是锁释放唤醒,因为如果中断唤醒的节点仍然存在Condition队列中,所以需要从Condition中删除
            if (node.nextWaiter != null) 
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

4.1.1 addConditionWaiter()

加入Condition队列方法,并没有像AQS队列中那样处理并发情况,是因为在操作Condition的时候当前线程已经获取了AQS独占的资源,所以不用考虑并发问题

   private Node addConditionWaiter() {
            Node t = lastWaiter;
            //1. 如果尾节点已经Cancel,直接清除。出现该情况
            //是线程被中断时或超时,await()方法中checkInterruptWhileWaiting方法调用
            //transferAfterCancelledWait导致
            if (t != null && t.waitStatus != Node.CONDITION) {
                //对t.waitStatus != Node.CONDITION的节点进行删除
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            //把当前节点封装成NODE放入Condition队列
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

4.1.2 unlinkCancelledWaiters()

清除Condition队列中因超时或者中断而还存在的点(这些节点不是Condition应该被删除)

    private void unlinkCancelledWaiters() {
            Node t = firstWaiter;
            Node trail = null;
            while (t != null) {
                Node next = t.nextWaiter;
                if (t.waitStatus != Node.CONDITION) {
                    //如果节点不为Condition状态,则将对应节点的next删除
                    t.nextWaiter = null;
                    if (trail == null)
                        //next节点赋予fistWaiter相当于删除t节点
                        firstWaiter = next;
                    else
                        //同样也是删除t节点操作
                        trail.nextWaiter = next;
                    if (next == null)
                        lastWaiter = trail;
                }
                else
                    trail = t;
                //从下一个节点开始处理
                t = next;
            }
        }

4.1.3 isOnSyncQueue(Node)

final boolean isOnSyncQueue(Node node) {
        //如果节点状态是Condition或者node.prev为空则返回false,因为如果节点状态是Condition,说明该节点只会存在于Condition队列中,而之前说过AQS是个双向链表而Condition是个单向链表,而在入AQS队列之前会分配其前驱节点。
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        //同理因为在AQS队列中会分配node的next节点
        if (node.next != null)
            return true;
        //如果前面判断完了,则从同步队列中遍历判断是否有当前节点
        return findNodeFromTail(node);

4.2 signal()

将Condition队列中等待的线程节点,转移到AQS队列中

   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;
            //将first节点移动到AQS队列中
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }

    final boolean transferForSignal(Node node) {
        //CAS控制将节点状态转化为0
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;
        //调用之前AQS的enq方法将节点加入到AQS中
        Node p = enq(node);
        int ws = p.waitStatus;
        //并将节点状态处理成SIGNAL
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }

正常情况下ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)是不会触发的,所以线程一般不会在这里唤醒,只有在signal以后继续调用lock.unlock,由于节点在AQS队列中,如果获取锁资源则会被唤醒。

五、使用场景

5.1 顺序打印ABC问题

实现代码:

public class printer {

    private volatile char currentTheadName = 'a';
    private ReentrantLock lock = new ReentrantLock();

    Condition aCondition = lock.newCondition();
    Condition bCondition = lock.newCondition();
    Condition cCondition = lock.newCondition();



    public class printAThread implements Runnable{

        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (currentTheadName != 'a'){
                        aCondition.await();
                    }
                    System.out.println("第"+i+"次打印"+"Print A");
                    currentTheadName = 'b';
                    bCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public class printBThread implements Runnable{

        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (currentTheadName != 'b'){
                        bCondition.await();
                    }
                    System.out.println("第"+i+"次打印"+"Print B");
                    currentTheadName = 'c';
                    cCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }



    public class printCThread implements Runnable{

        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (currentTheadName != 'c'){
                        cCondition.await();
                    }
                    System.out.println("第"+i+"次打印"+"Print C");
                    currentTheadName = 'a';
                    aCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        printer printer = new printer();
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.execute(printer.new printAThread());
        service.execute(printer.new printBThread());
        service.execute(printer.new printCThread());

        service.shutdown();
    }

}

返回结果:

第1次打印Print A
第1次打印Print B
第1次打印Print C
第2次打印Print A
第2次打印Print B
第2次打印Print C
第3次打印Print A
第3次打印Print B
第3次打印Print C
第4次打印Print A
第4次打印Print B
第4次打印Print C
第5次打印Print A
第5次打印Print B
第5次打印Print C
第6次打印Print A
第6次打印Print B
第6次打印Print C
第7次打印Print A
第7次打印Print B
第7次打印Print C
第8次打印Print A
第8次打印Print B
第8次打印Print C
第9次打印Print A
第9次打印Print B
第9次打印Print C

5.2 生产者和消费者问题

public class ProducerAndConsumer {

    private static List bufferList = new ArrayList();

    private static final int MAX_SIZE = 10;

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition empty = lock.newCondition();
    private static Condition full = lock.newCondition();

    public class Producer implements Runnable{

        public void run() {
            lock.lock();
            try {
                while (bufferList.size() >= MAX_SIZE){
                    System.out.println("buff is full");
                    empty.await();
                }
                bufferList.add(new Object());
                System.out.println("producer produce one , buffe size is " + bufferList.size());
                full.signalAll();
            } catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public class Consumer implements Runnable{

        public void run() {
            lock.lock();
            try {
                while (bufferList.size() <= 0){
                    System.out.println("buff is empty");
                    full.await();
                }
                bufferList.remove(0);
                System.out.println("consume the head one , buffe size is " + bufferList.size());
                empty.signalAll();
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }

    public static void main(String[] args) {
        ProducerAndConsumer producerAndConsumer = new ProducerAndConsumer();
        int producerCount = 10;

        int consumer = 6;

        for (int j = 0 ; j <= consumer ; j++){
            new Thread(producerAndConsumer.new Consumer()).start();
        }
        
        for (int i = 0 ; i <= producerCount ; i++){
            new Thread(producerAndConsumer.new Producer()).start();
        }
    }
}
 
 

返回结果:

buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
producer produce one , buffe size is 1
consume the head one , buffe size is 0
buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
producer produce one , buffe size is 1
consume the head one , buffe size is 0
buff is empty
buff is empty
buff is empty
buff is empty
buff is empty
producer produce one , buffe size is 1
producer produce one , buffe size is 2
consume the head one , buffe size is 1
consume the head one , buffe size is 0
buff is empty
buff is empty
buff is empty
producer produce one , buffe size is 1
consume the head one , buffe size is 0
buff is empty
buff is empty
producer produce one , buffe size is 1
consume the head one , buffe size is 0
buff is empty
producer produce one , buffe size is 1
consume the head one , buffe size is 0
producer produce one , buffe size is 1
producer produce one , buffe size is 2
producer produce one , buffe size is 3
producer produce one , buffe size is 4

你可能感兴趣的:(java并发包之Condition)