08-AQS之ReentrantLock

AQS原理分析

什麼是AQS

java.util.concurrent包中的大多數同步器實現都是圍繞着共同的基礎行爲,比如等待隊列、條件隊列、獨佔獲取、共享獲取等,而這些行爲的抽象就是基於AbstractQueuedSynchronizer(簡稱AQS)實現的,AQS是一個抽象同步框架,可以用來實現一個依賴狀態的同步器。

JDK中提供的大多數的同步器如Lock, Latch, Barrier等,都是基於AQS框架來實現的

  • 一般是通過一個內部類Sync繼承 AQS
  • 將同步器所有調用都映射到Sync對應的方法

image

AQS具備的特性:

  • 阻塞等待隊列
  • 共享/獨佔
  • 公平/非公平
  • 可重入
  • 允許中斷

AQS內部維護屬性volatile int state

  • state表示資源的可用狀態

State三種訪問方式:

  • getState()
  • setState()
  • compareAndSetState()

AQS定義兩種資源共享方式

  • Exclusive-獨佔,只有一個線程能執行,如ReentrantLock
  • Share-共享,多個線程可以同時執行,如Semaphore/CountDownLatch

AQS定義兩種隊列

  • 同步等待隊列: 主要用於維護獲取鎖失敗時入隊的線程
  • 條件等待隊列: 調用await()的時候會釋放鎖,然後線程會加入到條件隊列,調用signal()喚醒的時候會把條件隊列中的線程節點移動到同步隊列中,等待再次獲得鎖

AQS 定義了5個隊列中節點狀態:

  1. 值爲0,初始化狀態,表示當前節點在sync隊列中,等待着獲取鎖。
  2. CANCELLED,值爲1,表示當前的線程被取消;
  3. SIGNAL,值爲-1,表示當前節點的後繼節點包含的線程需要運行,也就是unpark;
  4. CONDITION,值爲-2,表示當前節點在等待condition,也就是在condition隊列中;
  5. PROPAGATE,值爲-3,表示當前場景下後續的acquireShared能夠得以執行;

不同的自定義同步器競爭共享資源的方式也不同。自定義同步器在實現時只需要實現共享資源state的獲取與釋放方式即可,至於具體線程等待隊列的維護(如獲取資源失敗入隊/喚醒出隊等),AQS已經在頂層實現好了。自定義同步器實現時主要實現以下幾種方法:

  • isHeldExclusively():該線程是否正在獨佔資源。只有用到condition才需要去實現它。
  • tryAcquire(int):獨佔方式。嘗試獲取資源,成功則返回true,失敗則返回false。
  • tryRelease(int):獨佔方式。嘗試釋放資源,成功則返回true,失敗則返回false。
  • tryAcquireShared(int):共享方式。嘗試獲取資源。負數表示失敗;0表示成功,但沒有剩餘可用資源;正數表示成功,且有剩餘資源。
  • tryReleaseShared(int):共享方式。嘗試釋放資源,如果釋放後允許喚醒後續等待結點返回true,否則返回false。

同步等待隊列

AQS當中的同步等待隊列也稱CLH隊列,CLH隊列是Craig、Landin、Hagersten三人發明的一種基於雙向鏈表數據結構的隊列,是FIFO先進先出線程等待隊列,Java中的CLH隊列是原CLH隊列的一個變種,線程由原自旋機制改爲阻塞機制。

AQS 依賴CLH同步隊列來完成同步狀態的管理:

  • 當前線程如果獲取同步狀態失敗時,AQS則會將當前線程已經等待狀態等信息構造成一個節點(Node)並將其加入到CLH同步隊列,同時會阻塞當前線程
  • 當同步狀態釋放時,會把首節點喚醒(公平鎖),使其再次嘗試獲取同步狀態。
  • 通過signal或signalAll將條件隊列中的節點轉移到同步隊列。(由條件隊列轉化爲同步隊列)

image

條件等待隊列

AQS中條件隊列是使用單向列表保存的,用nextWaiter來連接:

  • 調用await方法阻塞線程;
  • 當前線程存在於同步隊列的頭結點,調用await方法進行阻塞(從同步隊列轉化到條件隊列)

Condition接口詳解

image

  1. 調用Condition#await方法會釋放當前持有的鎖,然後阻塞當前線程,同時向Condition隊列尾部添加一個節點,所以調用Condition#await方法的時候必須持有鎖。
  2. 調用Condition#signal方法會將Condition隊列的首節點移動到阻塞隊列尾部,然後喚醒因調用Condition#await方法而阻塞的線程(喚醒之後這個線程就可以去競爭鎖了),所以調用Condition#signal方法的時候必須持有鎖,持有鎖的線程喚醒被因調用Condition#await方法而阻塞的線程。

等待喚醒機制之await/signal測試

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 等待喚醒機制 await/signal測試
 */
@Slf4j
public class ConditionTest {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                log.debug(Thread.currentThread().getName() + " 開始處理任務");
                //會釋放當前持有的鎖,然後阻塞當前線程
                condition.await();
                log.debug(Thread.currentThread().getName() + " 結束處理任務");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                log.debug(Thread.currentThread().getName() + " 開始處理任務");

                Thread.sleep(2000);
                //喚醒因調用Condition#await方法而阻塞的線程
                condition.signal();
                log.debug(Thread.currentThread().getName() + " 結束處理任務");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();


    }
}

結果

18:55:50.720 [Thread-0] DEBUG com.yoocar.jucdemo.lock.ConditionTest - Thread-0 開始處理任務
18:55:50.722 [Thread-1] DEBUG com.yoocar.jucdemo.lock.ConditionTest - Thread-1 開始處理任務
18:55:52.737 [Thread-1] DEBUG com.yoocar.jucdemo.lock.ConditionTest - Thread-1 結束處理任務
18:55:52.737 [Thread-0] DEBUG com.yoocar.jucdemo.lock.ConditionTest - Thread-0 結束處理任務

ReentrantLock詳解

ReentrantLock是一種基於AQS框架的應用實現,是JDK中的一種線程併發訪問的同步手段,它的功能類似於synchronized是一種互斥鎖,可以保證線程安全。

相對於 synchronized, ReentrantLock具備如下特點:

  • 可中斷
  • 可以設置超時時間
  • 可以設置爲公平鎖
  • 支持多個條件變量
  • 與 synchronized 一樣,都支持可重入


image

順便總結了幾點synchronized和ReentrantLock的區別:

  • synchronized是JVM層次的鎖實現,ReentrantLock是JDK層次的鎖實現;
  • synchronized的鎖狀態是無法在代碼中直接判斷的,但是ReentrantLock可以通過ReentrantLock#isLocked判斷;
  • synchronized是非公平鎖,ReentrantLock是可以是公平也可以是非公平的;
  • synchronized是不可以被中斷的,而ReentrantLock#lockInterruptibly方法是可以被中斷的;
  • 在發生異常時synchronized會自動釋放鎖,而ReentrantLock需要開發者在finally塊中顯示釋放鎖;
  • ReentrantLock獲取鎖的形式有多種:如立即返回是否成功的tryLock(),以及等待指定時長的獲取,更加靈活;
  • synchronized在特定的情況下對於已經在等待的線程是後來的線程先獲得鎖(回顧一下sychronized的喚醒策略),而ReentrantLock對於已經在等待的線程是先來的線程先獲得鎖;

ReentrantLock的使用

同步執行,類似於synchronized

ReentrantLock lock = new ReentrantLock(); //參數默認false,不公平鎖  
ReentrantLock lock = new ReentrantLock(true); //公平鎖  

//加鎖    
lock.lock(); 
try {  
    //臨界區 
} finally { 
    // 解鎖 
    lock.unlock();  
}

測試

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

/**
 * 同步執行
 */
public class ReentrantLockDemo {

    private static  int sum = 0;
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(()->{
                //加鎖
                lock.lock();
                try {
                    // 臨界區代碼
                    // TODO 業務邏輯:讀寫操作不能保證線程安全
                    for (int j = 0; j < 10000; j++) {
                        sum++;
                    }
                } finally {
                    // 解鎖
                    lock.unlock();
                }
            });
            thread.start();
        }

        Thread.sleep(2000);
        System.out.println(sum);
    }
}

可重入

import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 可重入
 */
@Slf4j
public class ReentrantLockDemo2 {

    public static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        method1();
    }


    public static void method1() {
        lock.lock();
        try {
            log.debug("execute method1");
            method2();
        } finally {
            lock.unlock();
        }
    }
    public static void method2() {
        lock.lock();
        try {
            log.debug("execute method2");
            method3();
        } finally {
            lock.unlock();
        }
    }
    public static void method3() {
        lock.lock();
        try {
            log.debug("execute method3");
        } finally {
            lock.unlock();
        }
    }
}

可中斷

import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 可中斷
 */
@Slf4j
public class ReentrantLockDemo3 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啓動...");

            try {
                lock.lockInterruptibly();
                try {
                    log.debug("t1獲得了鎖");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("t1等鎖的過程中被中斷");
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(1000);

            t1.interrupt();
            log.debug("線程t1執行中斷");
        } finally {
            lock.unlock();
        }

    }

}
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 可中斷
 */
@Slf4j
public class ReentrantLockDemo3 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啓動...");

            try {
                lock.lockInterruptibly();
                try {
                    log.debug("t1獲得了鎖");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("t1等鎖的過程中被中斷");
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(1000);

            t1.interrupt();
            log.debug("線程t1執行中斷");
        } finally {
            lock.unlock();
        }

    }

}
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 可中斷
 */
@Slf4j
public class ReentrantLockDemo3 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啓動...");

            try {
                lock.lockInterruptibly();
                try {
                    log.debug("t1獲得了鎖");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("t1等鎖的過程中被中斷");
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(1000);

            t1.interrupt();
            log.debug("線程t1執行中斷");
        } finally {
            lock.unlock();
        }

    }

}

結果

19:05:14.930 [main] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo3 - main線程獲得了鎖
19:05:14.934 [t1] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo3 - t1啓動...
19:05:15.949 [main] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo3 - 線程t1執行中斷
19:05:15.950 [t1] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo3 - t1等鎖的過程中被中斷
java.lang.InterruptedException
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
	at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
	at com.yoocar.jucdemo.lock.ReentrantLockDemo3.lambda$main$0(ReentrantLockDemo3.java:22)
	at java.lang.Thread.run(Thread.java:748)

鎖超時

立即失敗

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 鎖超時
 */
@Slf4j
public class ReentrantLockDemo4 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {

            log.debug("t1啓動...");
            // 注意: 即使是設置的公平鎖,此方法也會立即返回獲取鎖成功或失敗,公平策略不生效
//            if (!lock.tryLock()) {
//                log.debug("t1獲取鎖失敗,立即返回false");
//                return;
//            }

            //超時
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("等待 1s 後獲取鎖失敗,返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }

            try {
                log.debug("t1獲得了鎖");
            } finally {
                lock.unlock();
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            Thread.sleep(1000);
        } finally {
            lock.unlock();
        }

    }

}

結果

19:07:39.080 [main] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo4 - main線程獲得了鎖
19:07:39.082 [t1] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo4 - t1啓動...
19:07:40.084 [t1] DEBUG com.yoocar.jucdemo.lock.ReentrantLockDemo4 - 等待 1s 後獲取鎖失敗,返回

超時失敗

@Slf4j
public class ReentrantLockDemo4 {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.debug("t1啓動...");
            //超時
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("等待 1s 後獲取鎖失敗,返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            try {
                log.debug("t1獲得了鎖");
            } finally {
                lock.unlock();
            }

        }, "t1");


        lock.lock();
        try {
            log.debug("main線程獲得了鎖");
            t1.start();
            //先讓線程t1執行
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
        }

    }
}

結果

公平鎖
image

ReentrantLock 默認是不公平的

@Slf4j
public class ReentrantLockDemo5 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock(true); //公平鎖 

        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.debug(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }
        // 1s 之後去爭搶鎖
        Thread.sleep(1000);

        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    log.debug(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "強行插入" + i).start();
        }
    }
 }

結果

image

思考:ReentrantLock公平鎖和非公平鎖的性能誰更高?

條件變量

java.util.concurrent類庫中提供Condition類來實現線程之間的協調。調用Condition.await() 方法使線程等待,其他線程調用Condition.signal() 或 Condition.signalAll() 方法喚醒等待的線程。

注意:調用Condition的await()和signal()方法,都必須在lock保護之內。

@Slf4j
public class ReentrantLockDemo6 {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition cigCon = lock.newCondition();
    private static Condition takeCon = lock.newCondition();

    private static boolean hashcig = false;
    private static boolean hastakeout = false;

    //送煙
    public void cigratee(){
        lock.lock();
        try {
            while(!hashcig){
                try {
                    log.debug("沒有煙,歇一會");
                    cigCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            log.debug("有煙了,幹活");
        }finally {
            lock.unlock();
        }
    }

    //送外賣
    public void takeout(){
        lock.lock();
        try {
            while(!hastakeout){
                try {
                    log.debug("沒有飯,歇一會");
                    takeCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            log.debug("有飯了,幹活");
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo6 test = new ReentrantLockDemo6();
        new Thread(() ->{
            test.cigratee();
        }).start();

        new Thread(() -> {
            test.takeout();
        }).start();

        new Thread(() ->{
            lock.lock();
            try {
            	//有煙了
                hashcig = true;
                //喚醒送煙的等待線程
                cigCon.signal();
            }finally {
                lock.unlock();
            }


        },"t1").start();

        new Thread(() ->{
            lock.lock();
            try {
            	//有飯了
                hastakeout = true;
                //喚醒送飯的等待線程
                takeCon.signal();
            }finally {
                lock.unlock();
            }
        },"t2").start();
    }
}

結果

image

ReentrantLock源碼分析

關注點:

  • ReentrantLock加鎖解鎖的邏輯
  • 公平和非公平,可重入鎖的實現
  • 線程競爭鎖失敗入隊阻塞邏輯和獲取鎖的線程釋放鎖喚醒阻塞線程競爭鎖的邏輯實現 ( 設計的精髓:併發場景下入隊和出隊操作)

ReentrantLock加鎖邏輯

ReentrantLock reentrantLock=new ReentrantLock();
reentrantLock.lock();

非公平鎖的實現

CAS嘗試加鎖,加鎖成功,將State=1

static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    /**
     * Performs lock.  Try immediate barge, backing up to normal
     * acquire on failure.
     */
    final void lock() {
    	//直接CAS
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

CAS嘗試加鎖,加鎖失敗,入隊,阻塞

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
        	//添加到等待隊列
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
tryAcquire

嘗試獲取鎖

protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}

final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    //重入鎖,每次+1
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}
acquireQueued
Node
static final class Node {
   
   //共享
    static final Node SHARED = new Node();
    
    //獨佔
    static final Node EXCLUSIVE = null;

    //都是waitStatus的狀態
    static final int CANCELLED =  1;
    
    static final int SIGNAL    = -1;
    
    static final int CONDITION = -2;
    
    static final int PROPAGATE = -3;

    
    volatile int waitStatus;

    //鏈表的前置節點
    volatile Node prev;

    //鏈表的後置節點
    volatile Node next;

    //當前線程
    volatile Thread thread;

    
    Node nextWaiter;

    
    final boolean isShared() {
        return nextWaiter == SHARED;
    }

    
    final Node predecessor() throws NullPointerException {
        Node p = prev;
        if (p == null)
            throw new NullPointerException();
        else
            return p;
    }

    Node() {    // Used to establish initial head or SHARED marker
    }

    Node(Thread thread, Node mode) {     // Used by addWaiter
        this.nextWaiter = mode;
        this.thread = thread;
    }

    Node(Thread thread, int waitStatus) { // Used by Condition
        this.waitStatus = waitStatus;
        this.thread = thread;
    }
}
addWaiter

創建節點併入隊

/**
 * Creates and enqueues node for current thread and given mode.
 *
 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
 * @return the new node
 */
private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);
    //第一次的時候tail=null
    Node pred = tail=null;
    if (pred != null) {
        node.prev = pred;
        if (compareAndSetTail(pred, node)) {
            pred.next = node;
            return node;
        }
    }
    //將node初始化
    enq(node);
    return node;
}

enq

設置node鏈表,如果沒有鏈表,則將頭結點和尾結點都設置成node

private Node enq(final Node node) {
    for (;;) {
        Node t = tail;
        //沒有尾結點
        if (t == null) { // Must initialize
        	//初始化鏈表,將頭結點和尾結點都設置成node
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            //將node設置到原鏈表的尾結點後面
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}
acquireQueued
final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        //這裏的for循環非常重要,確保node節點可以阻塞和可以中斷
        for (;;) {
        	//取到head節點
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            //阻塞
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

shouldParkAfterFailedAcquire

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;
    //Status=-1是,返回true,表示可以阻塞
    if (ws == Node.SIGNAL)
        /*
         * This node has already set status asking a release
         * to signal it, so it can safely park.
         */
        return true;
    if (ws > 0) {
        /*
         * Predecessor was cancelled. Skip over predecessors and
         * indicate retry.
         */
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
        /*
         * waitStatus must be 0 or PROPAGATE.  Indicate that we
         * need a signal, but don't park yet.  Caller will need to
         * retry to make sure it cannot acquire before parking.
         */
         //將pred節點的Status設置成-1,表示可以阻塞
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
}

parkAndCheckInterrupt

private final boolean parkAndCheckInterrupt() {
	//掛起當前線程,阻塞線程,內部可以識別中斷
    LockSupport.park(this);
    return Thread.interrupted();
}

ReentrantLock釋放鎖邏輯

ReentrantLock reentrantLock=new ReentrantLock();
....
reentrantLock.unlock();

unlock()

public void unlock() {
    sync.release(1);
}

release

public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}

tryRelease

protected final boolean tryRelease(int releases) {
	//c=0
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {
        free = true;
        //用於重入鎖
        setExclusiveOwnerThread(null);
    }
    //setState=0
    setState(c);
    return free;
}

unparkSuccessor

private void unparkSuccessor(Node node) {
    /*
     * If status is negative (i.e., possibly needing signal) try
     * to clear in anticipation of signalling.  It is OK if this
     * fails or if status is changed by waiting thread.
     */
    int ws = node.waitStatus;
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);

    /*
     * Thread to unpark is held in successor, which is normally
     * just the next node.  But if cancelled or apparently null,
     * traverse backwards from tail to find the actual
     * non-cancelled successor.
     */
    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
        s = null;
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)
                s = t;
    }
    if (s != null)
    	//喚醒線程
        LockSupport.unpark(s.thread);
}

當然其中還有很多鏈表的操作,後面有時間了再研究

https://www.processon.com/view/link/6191f070079129330ada1209

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章