您的位置:首页 > 财经 > 金融 > 可见性::

可见性::

2025/4/21 7:51:36 来源:https://blog.csdn.net/xjdkxnhcoskxbco/article/details/140701311  浏览:    关键词:可见性::

目录

定义:

解决方法:

①使用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;}
}

 执行结果:执行两秒

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com