开源中国博客地址
本人小白,看到资料说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
通过结果可以知道其存入的元素哪怕是引用类型对象,也是线程安全的
新闻热点
疑难解答