如何在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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP