Java ConcurrentHashMap存入引用對象時也是線程安全的

本人小白,看到資料說ConcurrentHashMap是線程安全的,get過程不須要加鎖,put是線程安全的,推薦高併發時使用.可是本人不清楚是否該map中存入的引用類型對象,對象屬性變化也是否線程安全的,看了不少資料,貌似都沒說明這一點,因此寫代碼測試一下,java

 

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();

    }


}
相關文章
相關標籤/搜索