日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java锁之可重入锁介绍

發布時間:2025/3/12 java 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java锁之可重入锁介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

鎖作為并發共享數據,保證一致性的工具,在JAVA平臺有多種實現(如 synchronized 和 ReentrantLock等等 ) 。這些已經寫好提供的鎖為我們開發提供了便利,但是鎖的具體性質以及類型卻很少被提及。本系列文章將分析JAVA下常見的鎖名稱以及特性,為大家答疑解惑。

四、可重入鎖:

本文里面講的是廣義上的可重入鎖,而不是單指JAVA下的ReentrantLock。

可重入鎖,也叫做遞歸鎖,指的是同一線程 外層函數獲得鎖之后 ,內層遞歸函數仍然有獲取該鎖的代碼,但不受影響。
在JAVA環境下 ReentrantLock 和synchronized 都是 可重入鎖。

下面是使用實例:

public class Test implements Runnable{public synchronized void get(){System.out.println(Thread.currentThread().getId());set();}public synchronized void set(){System.out.println(Thread.currentThread().getId());}@Overridepublic void run() {get();}public static void main(String[] args) {Test ss=new Test();new Thread(ss).start();new Thread(ss).start();new Thread(ss).start();} }

兩個例子最后的結果都是正確的,即 同一個線程id被連續輸出兩次。

結果如下:

Threadid: 8 Threadid: 8 Threadid: 10 Threadid: 10 Threadid: 9 Threadid: 9 可重入鎖最大的作用是避免死鎖。
我們以自旋鎖作為例子。

public class SpinLock {private AtomicReference<Thread> owner =new AtomicReference<>();public void lock(){Thread current = Thread.currentThread();while(!owner.compareAndSet(null, current)){}}public void unlock (){Thread current = Thread.currentThread();owner.compareAndSet(current, null);} }

對于自旋鎖來說:

1、若有同一線程兩調用lock() ,會導致第二次調用lock位置進行自旋,產生了死鎖
說明這個鎖并不是可重入的。(在lock函數內,應驗證線程是否為已經獲得鎖的線程)
2、若1問題已經解決,當unlock()第一次調用時,就已經將鎖釋放了。實際上不應釋放鎖。
(采用計數次進行統計)

修改之后,如下:

public class SpinLock1 {private AtomicReference<Thread> owner =new AtomicReference<>();private int count =0;public void lock(){Thread current = Thread.currentThread();if(current==owner.get()) {count++;return ;}while(!owner.compareAndSet(null, current)){}}public void unlock (){Thread current = Thread.currentThread();if(current==owner.get()){if(count!=0){count--;}else{owner.compareAndSet(current, null);}}} } 該自旋鎖即為可重入鎖。




總結

以上是生活随笔為你收集整理的Java锁之可重入锁介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。