Javaは、書き込みスレッド-volitale直後に読むには

揮発性
スレッド変数は直ちにバックメインメモリに書き込まれた修正する後
代わりに緩衝液を、メインメモリから読み出されたスレッド変数読み出し、コマンド並べ替えを回避する場合

悪循環を断ち切ることができません

public class my {

private volatile static int num=0;
public static void main(String[]args) throws InterruptedException
{
    new Thread(()->{

        while(num==0)
        {

        }
    }).start();
    Thread.sleep(1000);
    num=1; //理论上1秒后停止,因为死循环没有办法同步num
}

}

更新:

public class my {

private volatile static int num=0;
public static void main(String[]args) throws InterruptedException
{
    new Thread(()->{

        while(num==0)
        {

        }
    }).start();
    Thread.sleep(1000);
    num=1; //理论上1秒后停止,因为死循环没有办法同步num
}

おすすめ

転載: blog.51cto.com/14437184/2430515