本人小白,看到资料说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();
1public void testFunc(){ 2 3 map.put("test",new TestModel(1)); 4 5 Thread thread = new Thread() { 6 @Override 7 public void run() { 8 int n=0; 9 while (n<100){ 10 System.out.println("线程1" + ":" + map.get("test"). getValue()); 11 map.get("test").setValue(map.get("test").getValue()+1); 12 n++; 13 //ConcurrentUtils.sleep(10); 14 try { 15 Thread.sleep(60); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 21 } 22 }; 23 thread.run(); 24 25 26 Thread thread1 = new Thread() { 27 @Override 28 public void run() { 29 int n = 0; 30 while(n<100) { 31 System.out.println("线程2" + ":" + map.get("test"). getValue()); 32 n++; 33 ConcurrentUtils.sleep(1); 34 } 35 } 36 }; 37 thread1.run(); 38 39}
}
结果如下:
线程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
通过结果可以知道其存入的元素哪怕是引用类型对象,也是线程安全的