Ниже приведен код. Он всегда должен выводить 1000. Но это не ожидаемое поведение.
Может кто-нибудь объяснить, почему оно так себя ведет?
Код: Выделить всё
Map map = new Hashtable();
map.put("key", 0);
Runnable task = () -> {
for (int i = 0; i < 10; i++) {
map.put("key", map.get("key")+1);
}
};
Thread[] threads = new Thread[100];
for (int i = 0; i < 100; i++) {
threads[i] = new Thread(task);
threads[i].start();
}
for (int i = 0; i < 100; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Hashtable value: " + map.get("key"));
Подробнее здесь: https://stackoverflow.com/questions/787 ... tion-issue