如何保证HashMap线程安全呢?
下文笔者讲述java代码中保证HashMap线程安全的方法及示例分享,如下所示
保证HashMap线程安全的方法
方式1:
使用synchronized关键字 对操作HashMap的方法进行包裹
方式2:
使用Collections.synchronizedMap方法包装HashMap
对HashMap进行同步控制
例:HashMap线程安全的操作示例
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HashMapSafeExample {
public static void main(String[] args) {
// 创建一个 HashMap 实例,并使用 Collections.synchronizedMap 方法包装它
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<>());
// 创建两个线程,同时对 HashMap 进行 put 操作
Thread thread1 = new Thread(() -> {
synchronized (map) {
for (int i = 0; i < 1000; i++) {
map.put("Key" + i, i);
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (map) {
for (int i = 1000; i < 2000; i++) {
map.put("Key" + i, i);
}
}
});
// 启动线程
thread1.start();
thread2.start();
// 等待两个线程执行完毕
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 输出 HashMap 的大小
System.out.println("HashMap size: " + map.size());
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


