如何在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();
//显示元素
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