如何在Java中建立執行緒安全的類?


執行緒安全的類是一種類,它可以確保類的內部狀態以及方法返回的值是正確的,同時可以從多個執行緒同時呼叫。

HashMap是一個非同步集合類。如果我們需要對其執行執行緒安全操作,那麼必須明確對其進行同步。

示例

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

public class HashMapSyncExample {
   public static void main(String args[]) {

      HashMap hmap = new HashMap();
      hmap.put(2, "Raja");
      hmap.put(44, "Archana");
      hmap.put(1, "Krishna");
      hmap.put(4, "Vineet");
      hmap.put(88, "XYZ");

      Map map= Collections.synchronizedMap(hmap);
      Set set = map.entrySet();
      synchronized(map){
            Iterator i = set.iterator();
          // Display elements
         while(i.hasNext()) {
               Map.Entry me = (Map.Entry)i.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
         }
      }
   }
}

在上面的示例中,我們有一個HashMap,它具有整數鍵和String型別的鍵值。為了對其進行同步,我們正在使用Collections.synchronizedMap(hashmap)。它返回一個執行緒安全的對映,並由指定的HashMap作為後盾。

輸出

1: Krishna
2: Raja
4: Vineet
88: XYZ
44: Archana

更新時間:2019年7月30日

770次瀏覽

激發您的 事業

完成課程獲得證書

開始
廣告