一、目标
创建一个HashMap,创建两个线程,每个线程向map中存储50万条key值不一样的数据,最终map中应该存在100万条数据。
二、代码
package com.zjl.study.多线程.ConcurrentHashMap;
import java.util.HashMap;
import java.util.Map;
/**
* Created by zjl 2022/5/29
**/
public class ConcurrentHashMapDemo {
public static Map<String, String> map = new HashMap<>();
public static void main(String[] args) {
MyRunnable target = new MyRunnable();
Thread t1 = new Thread(target, "线程1");
Thread t2 = new Thread(target, "线程2");
t1.start();
t2.start();
try {
t1.join(); //让t1跑完,主线程不竞争t1的CPU
t2.join(); //让t2跑完,主线程不竞争t2的CPU
} catch (InterruptedException e) {
e.printStackTrace();
}
// 等两个线程跑完之后去获取集合的最终元素个数
System.out.println("map的元素个数为:" + map.size());
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 500000; i++) {
// 线程名 + i 作为key值,防止key值重复
ConcurrentHashMapDemo.map.put(Thread.currentThread().getName() + i, Thread.currentThread().getName() + i);
}
}
}
三、运行结果
四、结论
并发情况下HashMap存在线程安全问题。