java 多线程-volitale写后立即读

volatile
线程对变量进行修改后,立刻写回到主内存
线程对变量读取的时候,从主内存中读取,而不是缓冲,避免了指令重排

无法破除循环

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