温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

发布时间:2020-08-03 16:07:36 来源:网络 阅读:509 作者:shayang88 栏目:编程语言

1、Condition介绍

1.1 Condition是对线程的wait,notify的增强

1.2 在ReentrantLock中他的实现类是AQS中的ConditionObject,实现了Condition接口,利用AQS的节点,实现了条件队列。

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

2、案例分析

2.1 说明:Thread-1获取锁,然后await,释放锁;Thread-2获得锁,唤醒Thread-1,释放锁;Thread-1重新获取锁,释放锁。

2.2 代码

2.2.1 Thread-1

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Task1 implements Runnable{

    private ReentrantLock lock;
    private Condition con;

    public Task1(ReentrantLock lock, Condition con) {
        this.lock = lock;
        this.con = con;
    }

    @Override
    public void run() {

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取到锁....");
            System.out.println(Thread.currentThread().getName() + "开始阻塞....");
            con.await();
            System.out.println(Thread.currentThread().getName() + "重新获取锁,继续执行....");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放锁....");
            lock.unlock();
        }
    }
}

2.2.2 Thread-2

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Task2 implements Runnable{

    private ReentrantLock lock;
    private Condition con;

    public Task2(ReentrantLock lock, Condition con) {
        this.lock = lock;
        this.con = con;
    }

    @Override
    public void run() {

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取到锁....");
            System.out.println(Thread.currentThread().getName() + "唤醒Thread-1....");
            con.signal();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放锁....");
            lock.unlock();
        }
    }
}

2.2.3 启动文件

import java.text.ParseException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main {

    public static void main(String[] args) throws ParseException, InterruptedException {
        ReentrantLock lock = new ReentrantLock(true);
        Condition condition = lock.newCondition();
        Thread t1 = new Thread(new Task1(lock,condition),"Thread-1");
        Thread.sleep(2000);
        Thread t2 = new Thread(new Task2(lock,condition),"Thread-2");
        t1.start();
        t2.start();
    }
}

2.2.4 运行结果

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

3、源码分析

3.1 获取锁的源码在上一篇已经分析过了,来看await操作:

public final void await() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException(); //判断线程是否中断,中断则抛出异常
        Node node = addConditionWaiter(); //当前线程包装节点,放入【条件对列】,注意不是【等待队列】
        int savedState = fullyRelease(node);//释放锁资源
        int interruptMode = 0;
        while (!isOnSyncQueue(node)) { //如果当前节点不在【等待队列】
            LockSupport.park(this); //在这里阻塞,等待被唤醒,后面代码唤醒前不执行
            if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                break;
        }
        if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
            interruptMode = REINTERRUPT;
        if (node.nextWaiter != null) // clean up if cancelled
            unlinkCancelledWaiters();
        if (interruptMode != 0)
            reportInterruptAfterWait(interruptMode);
    }

3.1.1 await()方法会释放当前线程持有的锁,就是fullyRelease方法的作用

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

3.1.2 线程A释放了锁,并进入条件对列,处于阻塞状态。

3.2 Thread-2获取到锁后,调用signal方法唤醒Thread-1

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)
多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        //将节点的状态修改为0,从【条件队列】节点状态转换为【等待队列】默认节点状态0,节点可以插入【等待队列】
        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;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) //将前驱节点设置为可唤醒状态
            LockSupport.unpark(node.thread);//唤醒节点,也就是Thread-1
        return true;
    }

3.3 Thread-2释放锁

3.3.1Thread-2释放锁,会唤醒【等待队列】的首节点,参看上一篇介绍(unparkSuccessor方法)

3.3.2 Thread-1继续执行

多线程(十一、AQS原理-ReentrantLock的条件队列Condition)

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI