尽管更新了值,线程仍然无限循环

时间:2017-05-13 17:45:21

标签: java

我的朋友向我提出了一个问题,并被要求解释为什么程序可能会无限循环。

public class Test {
    private static boolean flag;
    private static int count;

    private static class ReaderThread extends Thread {
        public void run() {
            while (!flag)
                Thread.yield();
            System.out.println(count);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().start();
        count = 1;
        flag = true;
    }
}

我确信它不可能发生。但实际上它确实发生了一次(可能是50次)。

我无法解释这种行为。我有什么遗失吗?

1 个答案:

答案 0 :(得分:8)

来自书籍 - Java Concurrency In Practice(这个例子似乎取自本书)。

当读取和写入发生在不同的线程中时,无法保证读取线程会及时看到另一个线程写入的值,甚至根本不会保证读取线程可能会缓存这些值。 为了确保跨线程的内存写入的可见性,您必须使用 同步 或将变量声明为 volatile 。< / p>