怎样证明HashMap不是线程安全的 博客分类: javaweb
HashMap用在方法内部并且不传到方法外面可以用HashMap,如果HashMap作为类的成员变量或静态属性
要为HashMap加线程安全锁Collections.synchronizedMap(new HashMap());
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static final Map<String, String> hashMap = Collections.synchronizedMap(new HashMap<String, String>());
public static void main(String[] args) throws InterruptedException {
// 线程一
Thread t1 = new Thread() {
public void run() {
for (int i = 0; i < 25; i++) {
hashMap.put(String.valueOf(i), String.valueOf(i));
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int j = 25; j < 50; j++) {
hashMap.put(String.valueOf(j), String.valueOf(j));
}
}
};
t1.start();
t2.start();
// 主线程休眠1秒钟
Thread.currentThread().sleep(1000);
System.out.println("size---" + hashMap.size());
for (int l = 0; l < 50; l++) {
System.err.println(String.valueOf(l) + ":" + hashMap.get(String.valueOf(l)));
}
}
}