可见性::

目录

定义:

解决方法:

①使用synchronized实现缓存和内存的同步

修改一:

加入语句:

代码:

修改2:

在代码块中加入:

代码:

执行结果:

原因:

②使用volatile实现变量可见性 


定义:

当多个线程访问同一个变量的时候,一个线程修改了这个变量的值,其他线程肯呢个看不到立即修改的值,他们之间存在着不可见的问题

导致这个的问题在于,多核cpu的多个核之间他们的高速缓存并不会共享,而各自运算的无数据肯呢个存在各自的高速缓存中

解决方法:

①使用synchronized实现缓存和内存的同步

public class Test1 {
    public  static Boolean always = true;
    public static void main(String[] args) {
       //子线程
        new Thread(()->{
           while (always){//主线程中修改了always的值,在子线程中没看到
             
           }

       }).start();
        try {
            Thread.sleep(2000);//主线程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        always=false;

    }
}

执行结果:程序一直运行,不结束,主线程中修改了always的值,在子线程中没看到

修改一:

加入语句:
 synchronized (always){}
代码:
public class Test1 {
    public  static Boolean always = true;
    public static void main(String[] args) {
       //子线程
        new Thread(()->{
           while (always){
             
              synchronized (always){}
           }

       }).start();
        try {
            Thread.sleep(2000);//主线程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        always=false;

    }
}

执行结果:运行两秒钟结束

原因是,同步了always语句修改的结果

修改2:

在代码块中加入:
System.out.println("hello");
代码:
public class Test1 {
    public  static Boolean always = true;
    public static void main(String[] args) {
       //子线程
        new Thread(()->{
           while (always){
             
               System.out.println("hello");
           }

       }).start();
        try {
            Thread.sleep(2000);//主线程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        always=false;

    }
}
执行结果:

打印两秒钟hello,结束 

原因:

println函数中包含了sychronized,解决了可见性问题 

②使用volatile实现变量可见性 

定义变量的时候使用volatile

 public volatile static Boolean always = true;

代码:

public class Test1 {
    public volatile static Boolean always = true;
    public static void main(String[] args) {
       //子线程
        new Thread(()->{
           while (always){

                      }

       }).start();
        try {
            Thread.sleep(2000);//主线程
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        always=false;

    }
}

 执行结果:执行两秒

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值