Lance提问笔记:关于map的多线程操作

package mthashmap;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Ay叔  一个static 的MAP 里面 存了一个 实例..两条线程访问这个MAP 取这实例. 那么取到的是同一个 还是 两个不同的实例?
 * Created by zhida on 2015/2/12.
 */
public class MT_HashMap {
public  static ConcurrentHashMap<String, value> map = new ConcurrentHashMap<String, value>();

    public static void main (String[] args){
map.put("key",new value("value"));
        new Thread(new Runnable(){
@Override
public synchronized void run() {
                value v = map.get("key");
System.out.println("mt1 oldkey=" + v);
                try {
                    Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
                    e.printStackTrace();
}
                System.out.println("mt1 mapkey = "+map.get("key"));
System.out.println("mt1 key="+v);
//                map.put("key",new value("old value"));
v.set("old value");
}
        }).start();
        new Thread(new Runnable(){
@Override
public synchronized void run() {
try {
                    Thread.currentThread().sleep(200);
value v = map.get("key");
System.out.println("mt2 key="+v);
v.set("new value");
//                map.put("key",new value("new value"));
System.out.println("mt2 mapkey="+map.get("key"));
Thread.currentThread().sleep(1500);
System.out.println("mt2 key="+v);
} catch (InterruptedException e) {
                    e.printStackTrace();
}

            }
        }).start();
}
static class value{
        String str;
        public value(String str){
this.str = str;
}
public void set(String str){
this.str = str;
}
public String toString(){
return str;
}
    }
}
原文地址:https://www.cnblogs.com/Ayanami-Blob/p/5375248.html