I'm reading "Java Concurrency in Practice". Section 3.1.1 talks about it may cause surprising results when you do not provide enough synchronization to your shared variables.
Take a look at the example in the book:
Explanations from the book:
NoVisibility could loop forever because the value of ready might never become visible to the reader thread. Even
more strangely, NoVisibility could print zero because the write to ready might be made visible to the reader thread
before the write to number, a phenomenon known as reordering. There is no guarantee that operations in one thread
will be performed in the order given by the program, as long as the reordering is not detectable from within that thread
even if the reordering is apparent to other threads. When the main thread writes first to number and then to done
without synchronization, the reader thread could see those writes happen in the opposite order or not at all.
Take a look at the example in the book:
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready) Thread.yield();
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
Explanations from the book:
NoVisibility could loop forever because the value of ready might never become visible to the reader thread. Even
more strangely, NoVisibility could print zero because the write to ready might be made visible to the reader thread
before the write to number, a phenomenon known as reordering. There is no guarantee that operations in one thread
will be performed in the order given by the program, as long as the reordering is not detectable from within that thread
even if the reordering is apparent to other threads. When the main thread writes first to number and then to done
without synchronization, the reader thread could see those writes happen in the opposite order or not at all.
本文深入探讨了在Java并发编程中,未充分同步共享变量可能导致的意外结果,通过具体实例展示了变量可见性和操作顺序的不确定性,强调了同步在并发编程中的关键作用。
550

被折叠的 条评论
为什么被折叠?



