溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

多線程(十一、AQS原理-ReentrantLock的條件隊列Condition)

發(fā)布時間:2020-08-03 16:07:36 來源:網(wǎng)絡(luò) 閱讀:500 作者:shayang88 欄目:編程語言

1、Condition介紹

1.1 Condition是對線程的wait,notify的增強

1.2 在ReentrantLock中他的實現(xiàn)類是AQS中的ConditionObject,實現(xiàn)了Condition接口,利用AQS的節(jié)點,實現(xiàn)了條件隊列。

多線程(十一、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() + "重新獲取鎖,繼續(xù)執(zhí)行....");
            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 運行結(jié)果

多線程(十一、AQS原理-ReentrantLock的條件隊列Condition)

3、源碼分析

3.1 獲取鎖的源碼在上一篇已經(jīng)分析過了,來看await操作:

public final void await() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException(); //判斷線程是否中斷,中斷則拋出異常
        Node node = addConditionWaiter(); //當前線程包裝節(jié)點,放入【條件對列】,注意不是【等待隊列】
        int savedState = fullyRelease(node);//釋放鎖資源
        int interruptMode = 0;
        while (!isOnSyncQueue(node)) { //如果當前節(jié)點不在【等待隊列】
            LockSupport.park(this); //在這里阻塞,等待被喚醒,后面代碼喚醒前不執(zhí)行
            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釋放了鎖,并進入條件對列,處于阻塞狀態(tài)。

3.2 Thread-2獲取到鎖后,調(diào)用signal方法喚醒Thread-1

多線程(十一、AQS原理-ReentrantLock的條件隊列Condition)
多線程(十一、AQS原理-ReentrantLock的條件隊列Condition)

final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        //將節(jié)點的狀態(tài)修改為0,從【條件隊列】節(jié)點狀態(tài)轉(zhuǎn)換為【等待隊列】默認節(jié)點狀態(tài)0,節(jié)點可以插入【等待隊列】
        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);//將節(jié)點插入【等待隊列】
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) //將前驅(qū)節(jié)點設(shè)置為可喚醒狀態(tài)
            LockSupport.unpark(node.thread);//喚醒節(jié)點,也就是Thread-1
        return true;
    }

3.3 Thread-2釋放鎖

3.3.1Thread-2釋放鎖,會喚醒【等待隊列】的首節(jié)點,參看上一篇介紹(unparkSuccessor方法)

3.3.2 Thread-1繼續(xù)執(zhí)行

多線程(十一、AQS原理-ReentrantLock的條件隊列Condition)

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI