码迷,mamicode.com
首页 > 编程语言 > 详细

java 多线程-volatile写后立即读

时间:2019-08-18 17:44:30      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:static   inter   volatile   public   read   dex   interrupt   停止   int   

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
}

java 多线程-volatile写后立即读

标签:static   inter   volatile   public   read   dex   interrupt   停止   int   

原文地址:https://blog.51cto.com/14437184/2430515

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!