日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ReentrantLock相較于synchronized的區別---鎖超時(源碼理解)

作者:ADRU 更新時間: 2024-02-16 編程語言

鎖超時原理介紹

ReentrantLock支持設置鎖等待超時時間,即在一定時間內未獲得鎖的線程可以選擇放棄等待,避免死鎖

通過查看tryLock()實現方法 發現加鎖的邏輯在doAcquireNanos中實現的,它接受兩個參數:arg表示獲取鎖時的參數,nanosTimeout表示最大等待時間(以納秒為單位)。

這個方法具體邏輯如下:

  1. 首先,線程會嘗試獲取鎖。如果鎖當前未被其他線程持有,則線程直接獲取鎖并返回true。

  2. 如果鎖被其他線程持有,線程將進入等待隊列,并啟動一個計時器,設置超時時間。

  3. 在等待過程中,線程可能會被其他線程中斷,或者等待時間達到設定的超時時間。如果發生這些情況,線程將停止等待,并返回false。

  4. 如果線程在超時時間內成功獲取了鎖,則停止計時器,并返回true。

代碼測試

先看沒有設置超時時間的情況

import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

public class Test02 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            System.out.println("線程1開始執行");
            if(!lock.tryLock()){
                System.out.println("線程1獲取鎖失敗");
                return;
            }
            try {
                System.out.println("線程1獲得了鎖");
            }finally {
                lock.unlock();
            }
        },"t1");
        lock.lock();
        System.out.println("主線程獲得了鎖");
        t1.start();
        try {
            sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

?執行結果如下:

?加上超時時間:

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

import static java.lang.Thread.sleep;

public class Test01 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println("嘗試獲得鎖");
            try {
                if (!lock.tryLock(2, TimeUnit.SECONDS)) {
                    System.out.println("獲取不到鎖");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("獲取不到鎖");
                return;
            }
            try {
                System.out.println("獲得到鎖");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        System.out.println("獲得到鎖");
        t1.start();
        sleep(1);
        System.out.println("釋放了鎖");
        lock.unlock();
    }
}

執行結果如下:

?

原文鏈接:https://blog.csdn.net/m0_71507863/article/details/136026581

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新