在 Java 中使用 volatile 关键字的完整示例? [英] Complete example for use of volatile key word in Java?

查看:31
本文介绍了在 Java 中使用 volatile 关键字的完整示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个在 Java 中使用 volatile 关键字的简单示例,由于不使用 volatile 而导致行为不一致.

I need a simple example of use of the volatile keyword in Java, behaving inconsistently as a result of not using volatile.

volatile 用法的理论部分我已经很清楚了.

The theory part of volatile usage is already clear to me.

推荐答案

首先,由于非易失性变量,没有保证公开缓存的方式.您的 JVM 可能一直对您非常友好,并且有效地将每个变量视为 volatile.

First of all, there's no guaranteed way of exposing caching due to non-volatile variables. Your JVM might just be very kind to you all the time and effectively treat every variable as volatile.

话虽如此,有几种方法可以增加线程缓存自己版本的非易失性变量的可能性.这是一个程序,它在我测试过的大多数机器中暴露了 volatile 的重要性(改编版本来自 此处):

That being said, there are a few ways to increase probability of having threads caching their own versions of a non-volatile variable. Here is a program that exposes the importance of volatile in most machines I've tested it on (adapted version 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 set to false.

然后继续运行.将 keepRunning 设为 volatile 会导致它打印

and continue running. Making keepRunning volatile causes it to print

keepRunning set to false.
Thread terminated.

并终止.

这篇关于在 Java 中使用 volatile 关键字的完整示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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