78. 同步访问共享的可变数据
本条主要是指出内存可见性,Java内存模型,重排序等机制引起可变对象共享的问题,这些都是并发的基础理论知识。
有时候这些错误不容易分析:
// Broken! - How long would you expect this program to run?
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(() -> {
int i = 0;
while (!stopRequested)
i++;
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);