網站首頁 編程語言 正文
鎖超時原理介紹
ReentrantLock支持設置鎖等待超時時間,即在一定時間內未獲得鎖的線程可以選擇放棄等待,避免死鎖
通過查看tryLock()實現方法 發現加鎖的邏輯在doAcquireNanos中實現的,它接受兩個參數:arg
表示獲取鎖時的參數,nanosTimeout
表示最大等待時間(以納秒為單位)。
這個方法具體邏輯如下:
-
首先,線程會嘗試獲取鎖。如果鎖當前未被其他線程持有,則線程直接獲取鎖并返回true。
-
如果鎖被其他線程持有,線程將進入等待隊列,并啟動一個計時器,設置超時時間。
-
在等待過程中,線程可能會被其他線程中斷,或者等待時間達到設定的超時時間。如果發生這些情況,線程將停止等待,并返回false。
-
如果線程在超時時間內成功獲取了鎖,則停止計時器,并返回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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-07-08 go語言代碼生成器code?generator使用示例介紹_Golang
- 2022-04-30 DataGridView清除顯示的數據、設定右鍵菜單_C#教程
- 2022-06-13 Docker鏡像的commit操作示例及作用_docker
- 2022-03-03 百度地圖 添加 左鍵菜單 Cannot read property 'remove' of unde
- 2022-12-07 C++?類this及返回自身對象的引用方式_C 語言
- 2022-08-02 shell?script獲取文件名或者目錄名稱的方法_linux shell
- 2023-01-29 python?index()?與?rindex()?方法的使用示例詳解_python
- 2022-10-23 Android?手寫RecyclerView實現列表加載_Android
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支