原 hashMap 线程不安全的演示和解决方案
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1132
package com.mszl.thread;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 功能:hashMap线程不安全的演示和解决方案
* 备注:更多资料请访问 http://www.91mszl.com
* @author bobo teacher
*/
public class HashMapDemo {
public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
for(int i=1; i<=50; i++){
Thread t=new Thread(new Runnable() {
@Override
public void run() {
String key=Thread.currentThread().getName();
String value=UUID.randomUUID().toString().substring(0, 8);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t" + map);
}
});
t.start();
}
}
}
执行结果:
java.util.ConcurrentModificationException
说明hashMap线程不安全。
二:hashMap线程不安全的解决方法。
(1)使用辅助类进行包装一层。Collections.synchronizedMap(new HashMap<String, String>())
package com.mszl.thread;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 功能:hashMap线程不安全的演示和解决方案
* 备注:更多资料请访问 http://www.91mszl.com
* @author bobo teacher
*/
public class HashMapDemo {
public static void main(String[] args) {
// Map<String, String> map=new HashMap<String, String>();
Map<String, String> map=Collections.synchronizedMap(new HashMap<String, String>());
// Map<String, String> map=new ConcurrentHashMap<String, String>();
for(int i=1; i<=50; i++){
Thread t=new Thread(new Runnable() {
@Override
public void run() {
String key=Thread.currentThread().getName();
String value=UUID.randomUUID().toString().substring(0, 8);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t" + map);
}
});
t.start();
}
}
}
(2)ConcurrentHashMap。
package com.mszl.thread;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 功能:hashMap线程不安全的演示和解决方案
* 备注:更多资料请访问 http://www.91mszl.com
* @author bobo teacher
*/
public class HashMapDemo {
public static void main(String[] args) {
// Map<String, String> map=new HashMap<String, String>();
// Map<String, String> map=Collections.synchronizedMap(new HashMap<String, String>());
Map<String, String> map=new ConcurrentHashMap<String, String>();
for(int i=1; i<=50; i++){
Thread t=new Thread(new Runnable() {
@Override
public void run() {
String key=Thread.currentThread().getName();
String value=UUID.randomUUID().toString().substring(0, 8);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t" + map);
}
});
t.start();
}
}
}
2019-11-26 15:13:29 阅读(865)
名师出品,必属精品 https://www.91mszl.com
博主信息