Java 中 volatile 关键字的最简单易懂的例子 [英] Simplest and understandable example of volatile keyword in Java

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

问题描述

我正在阅读 Java 中的 volatile 关键字并完全理解其中的理论部分.

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

但是,我正在寻找的是一个很好的例子,它显示了如果变量不是 volatile 会发生什么,如果它是.

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 (taken from here):

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,线程应该无限期地继续运行.但是,它会在几秒钟后停止.

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

我有两个基本问题:

  • 谁能用例子解释一下 volatile?与 JLS 的理论无关.
  • volatile 是同步的替代品吗?它是否实现了原子性?

推荐答案

Volatile --> 保证可见性而不是原子性

Volatile --> Guarantees visibility and NOT atomicity

同步(锁定) --> 保证可见性和原子性(如果做得好)

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

Volatile 不能替代同步

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

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

示例:

volatile int i = 0;

public void incrementI(){
   i++;
}

如果不使用同步或 AtomicInteger 将不是线程安全的,因为递增是一个复合操作.

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

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

Why program does not run indefinitely?

嗯,这取决于各种情况.在大多数情况下,JVM 足够智能以刷新内容.

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

正确使用 volatile 讨论了各种可能的用途挥发性的.正确使用 volatile 很棘手,我会说如有疑问,请忽略它",请改用同步块.

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.

还有:

同步块可以代替 volatile,但反之则不然.

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

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