public class Test implements Runnable{
private static Map<Integer, Integer> map = new ConcurrentHashMap<>();
@Override
public void run() {
update();
}
public void update(){
map.put(1,map.get(1)+1);
}
public static void main(String[] args) throws InterruptedException{
int i = 10000;
while (i > 0){
map.put(1, 1);
Test t = new Test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
if(map.get(1) != 5)
System.out.println(map.get(1));
i--;
}
}
}
有上面这个测试类. 但是对于结果表示很疑惑. 因为concurrentHashMap是线程安全的, 那么按照这个来做, 当上面这个测试类中的map被4个线程操作以后产生的结果应该为 map.get(1)=5 才对...但是从结果来看,并非都是如此啊. 这是什么原因造成的呢?