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

查看:44
本文介绍了为什么此代码在不使用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的情况下可以正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆