编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

为什么此代码在不使用volatile的情况下可以正常工作?:Why is this code working without volatile?

jack-hsueh 线程 2022-5-13 10:45 64人围观

腾讯云服务器
为什么此代码在不使用volatile的情况下可以正常工作?的处理方法

我是Java的新手,我目前正在学习 volatile .说我有以下代码:

I am new to Java, I am currently learning about volatile. Say I have the following code:

public class Test { private static boolean b = false; public static void main(String[] args) throws Exception { new Thread(new Runnable() { public void run() { while(true) { b = true; } } }).start(); // Give time for thread to start Thread.sleep(2000); System.out.println(b); } } 

输出:

true

此代码具有两个线程(主线程和另一个线程).为什么另一个线程能够修改 b 的值,而不应该将 b 设置为 volatile 以便做到这一点?

This code has two threads (the main thread and another thread). Why is the other thread able to modify the value of b, shouldn't b be volatile in order for this to happen?

问题解答

volatile 关键字保证更改在多个线程之间可见,但是您的解释是相反的意思也是如此.缺少 volatile 关键字可确保线程之间的隔离,并且没有这种保证.

The volatile keyword guarantees that changes are visible amongst multiple threads, but you're interpreting that to mean that opposite is also true; that the absence of the volatile keyword guarantees isolation between threads, and there's no such guarantee.

此外,尽管您的代码示例是多线程的,但不一定是并发的.可能是每个线程都缓存了这些值,但是在打印结果之前,JVM有足够的时间来传播更改.

Also, while your code example is multi-threaded, it isn't necessarily concurrent. It could be that the values were cached per-thread, but there was enough time for the JVM to propagate the change before you printed the result.

这篇关于为什么此代码在不使用volatile的情况下可以正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^