import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadMap {
private static Map map = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Integer result = new Random().nextInt();
map.put(Thread.currentThread(), result);//这里先设置值
System.out.println(Thread.currentThread() + " has put result = " + result);
new A().get();//这里取出值,为什么会有打印出null????
new B().get();//这里取出值,为什么会有打印出null????
}
}).start();
}
}
static class A {
public Integer get() {
Integer result = map.get(Thread.currentThread());
System.out.println(Thread.currentThread() + ", get result = " + result);
return result;
}
}
static class B {
public Integer get() {
Integer result = map.get(Thread.currentThread());
System.out.println(Thread.currentThread() + ", get result = " + result);
return result;
}
}
}
打印结果:
Thread[Thread-0,5,main] has put result = 2046069101
Thread[Thread-1,5,main] has put result = -1728516627
Thread[Thread-0,5,main], get result = null //这什么这里竟然有null
Thread[Thread-1,5,main], get result = -1728516627
Thread[Thread-0,5,main], get result = null //这什么这里竟然有null
Thread[Thread-1,5,main], get result = -1728516627