首页 > 代码库 > Java ConcurrentHashMap存入引用对象时也是线程安全的

Java ConcurrentHashMap存入引用对象时也是线程安全的

本人小白,看到资料说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();

    }


}

  

Java ConcurrentHashMap存入引用对象时也是线程安全的