雙檢查加鎖是一種設計模式,透過雙重檢查來確保執行緒安全,在Java 函數中可以這樣實作:定義一個靜態volatile 變數儲存實例;如果實例為空,則同步區塊內再檢查一次,為空則建立實例;傳回實例。實戰案例:在共享資源的場景(如快取類別)中,使用雙重檢查加鎖可以確保所有執行緒使用相同共享實例,避免資料競爭並保證資料完整性。

Java 函數中的雙重檢查加鎖:實作執行緒安全性的實際案例
雙重檢查加鎖是一個設計模式,它使用雙重檢查來確保只創建一次實例,從而實現多線程中的線程安全。以下是如何在Java 函數中實現雙重檢查加鎖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton. class ) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
|
登入後複製
實戰案例:線程共享資源
考慮一個線程共享資源的場景,例如一個緩存類,其中多個執行緒可以同時存取快取資料。為了避免資料競爭情況,我們需要確保快取物件只創建一次,並且所有執行緒都可以安全地存取它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class Cache {
private static volatile Cache instance;
public static Cache getInstance() {
if (instance == null) {
synchronized (Cache. class ) {
if (instance == null) {
instance = new Cache();
}
}
}
return instance;
}
}
List<String> sharedData = new ArrayList<>();
sharedData.add( "Item 1" );
sharedData.add( "Item 2" );
for (int i = 0; i < 10; i++) {
new Thread(() -> {
Cache cache = Cache.getInstance();
cache.put( "Key" + i, sharedData);
cache.get( "Key" + i);
}).start();
}
|
登入後複製
在上述範例中,Cache
類別使用雙重檢查加鎖,確保所有執行緒都使用相同共用實例。這樣可以避免建立多個快取實例,確保執行緒安全和資料的完整性。
以上是Java 函數中的雙重檢查加鎖如何實現線程安全?的詳細內容。更多資訊請關注PHP中文網其他相關文章!