開源中國博客地址
本人小白,看到資料說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
通過結果可以知道其存入的元素哪怕是引用類型對象,也是線程安全的
新聞熱點
疑難解答