本人小白,看到资料说ConcurrentHashMap是线程安全的,get过程不需要加锁,put是线程安全的,推荐高并发时使用.但是本人不清楚是否该map中存入的引用类型对象,对象属性变化也是否线程安全的,看了很多资料,貌似都没说明这一点,所以写代码测试一下,
package testConcurrentHashMap;
import java.util.concurrent.ConcurrentHashMap;
/** * Created by xuzimian on 17-3-1. */ public class testConcurrentHashMap { public ConcurrentHashMap<String,TestModel> map=new ConcurrentHashMap();
public void testFunc(){
map.put("test",new TestModel(1));
Thread thread = new Thread() {
@Override
public void run() {
int n=0;
while (n<100){
System.out.println("线程1" + ":" + map.get("test"). getValue());
map.get("test").setValue(map.get("test").getValue()+1);
n++;
//ConcurrentUtils.sleep(10);
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.run();
Thread thread1 = new Thread() {
@Override
public void run() {
int n = 0;
while(n<100) {
System.out.println("线程2" + ":" + map.get("test"). getValue());
n++;
ConcurrentUtils.sleep(1);
}
}
};
thread1.run();
}
}
结果如下:
线程1:1
线程1:2
线程1:3
线程1:4
线程1:5
线程1:6
线程1:7
线程1:8
线程1:9
线程1:10
线程1:11
线程1:12
线程1:13
......省略
线程1:100
线程2:101
......省略
线程2:101
线程2:101
通过结果可以知道其存入的元素哪怕是引用类型对象,也是线程安全的