在java中volatile关键字的简单和可理解的例子 [英] Simplest and understandable example of volatile keyword in java

查看:173
本文介绍了在java中volatile关键字的简单和可理解的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读关于volatile的volatile关键字,并完全理解它的理论部分。



但是,我正在寻找的是一个很好的例子



下面的代码片段不能正常工作( from aioobe

  class Test extends Thread {

boolean keepRunning = true;

public void run(){
while(keepRunning){
}

System.out.println(Thread terminated。
}

public static void main(String [] args)throws InterruptedException {
Test t = new Test();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println(keepRunning set to false。);
}
}

理想情况下,如果keepRunning不易变,线程应该继续不间断地运行。但是,它会在几秒钟后停止。



我有两个基本问题: -




  • 任何人都可以用示例解释volatile?不是来自JLS的理论。

  • 是同步的替代品吗?

    挥发性 - >保证可见性和非原子性



    同步(锁定) - >保证可见性和原子性(如果正确)



    替换同步



    仅当您更新引用而不对其执行其他操作时才使用volatile。



    示例:

      volatile int i = 0; 

    public void incrementI(){
    i ++;
    }

    不会是线程安全的,不使用同步或AtomicInteger,因为incrementing是一个化合物


    为什么程序不能无限期运行?


    这取决于各种情况。在大多数情况下,JVM足够聪明地刷新内容。



    正确使用volatile 讨论了volatile的各种可能的用法。使用volatile正确是棘手的,我会说如果有疑问,离开它,使用同步块代替。



    另外:



    同步块可用于替代volatile,但反转不为真


    I'm reading about volatile keyword in Java and completely understand the theory part of it.

    But, what I'm searching for is, a good case example, which shows what would happen if variable wasn't volatile and if it were.

    Below code snippet doesn't work as expected ( from aioobe)

    class Test extends Thread {
    
        boolean keepRunning = true;
    
        public void run() {
            while (keepRunning) {
            }
    
            System.out.println("Thread terminated.");
        }
    
        public static void main(String[] args) throws InterruptedException {
            Test t = new Test();
            t.start();
            Thread.sleep(1000);
            t.keepRunning = false;
            System.out.println("keepRunning set to false.");
        }
    }
    

    Ideally, if keepRunning wasn't volatile, thread should keep on running indefinetely. But, it does stop after few seconds.

    I've got two basic question :-

    • Can anyone explain volatile with example ? Not with theory from JLS.
    • Is volatile substitute for synchronization ? Does it achieve atomicity ?

    解决方案

    Volatile --> Guarantees visibility and NOT atomicity

    Synchronization (Locking) --> Guarantees visibility and atomicity (if done properly)

    Volatile is not a substitute for synchronization

    Use volatile only when you are updating the reference and not performing some other operations on it.

    Example:

    volatile int i = 0;
    
    public void incrementI(){
       i++;
    }
    

    will not be thread safe without use of synchronization or AtomicInteger as incrementing is an compound operation.

    Why program does not run indefinitely?

    Well that depends on various circumstances. In most cases JVM is smart enough to flush the contents.

    Correct use of volatile discusses various possible uses of volatile. Using volatile correctly is tricky, I would say "When in doubt, Leave it out", use synchronized block instead.

    Also:

    synchronized block can be used in place of volatile but the inverse is not true.

    这篇关于在java中volatile关键字的简单和可理解的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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