题目描述
为什么hashmap可以保证其元素node的可见性,下列代码线程B可以立马结束,我看起源码hashmap并没有使用volatile或加锁之类的,求大神解答,
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
public class b {
public static Map<Integer,Integer> map = new HashMap<>();
static {
map.put(1,2);
}
public static void main(String[] args) throws Exception {
Object o = new Object();
new Thread(() -> { //线程A
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(1,3);
}).start();
new Thread(() -> { //线程B
while (true) {
if (map.get(1)==3) {
System.out.println("结束");
break;
}
}
}).start();
}
}
不保证. 你观测到一次不叫"保证"了, 保证的相反是"不保证", 不是"保证不".
ConcurrentHashMap才保证