簡體   English   中英

為什么對非易失性的寫入對主線程可見?

[英]Why is the write to non-volatile visible to the main-thread?

想象一下下面的程序。

class Main {


    static class Whatever {
        int x = 0;
    }


    public static void main(String[] args) {
        Whatever whatever = new Whatever();

        Thread t = new Thread(() -> {
            whatever.x = 1;
        });
        t.start();
        try {
            t.join();
        }
        catch (InterruptedException e) {
        }

        System.out.println(whatever.x);
    }
}

主線程已緩存whatever ,並且x設置為0 另一個線程啟動,緩存whatever並將緩存的x設置為1

output 是

1

所以主線程已經看到了寫入。 這是為什么?

為什么對共享緩存進行了寫入,為什么主線程使其緩存無效以從共享緩存中讀取? 為什么我在這里不需要volatile

因為主線程加入它。 參見 JLS 中的 17.4.5:

線程中的所有操作都發生在任何其他線程從該線程上的 join() 成功返回之前。

順便說一句,沒有發生之前並不一定意味着某些東西不可見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM