Java:volatile足以使类线程安全吗? [英] Java: volatile enough to make classes threadsafe?

查看:1150
本文介绍了Java:volatile足以使类线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的volatile语句有疑问。请看这个构造的例子:

I have a question about the volatile statement in Java. Please look at this constructed example:

class Master {
    // Foo is a class with thread-safe methods
    public volatile Foo foo;
}

class Worker1 implements Runnable {
    protected Master master

    void run() { ... };
}

class Worker2 implements Runnable {
    protected Master master

    void run() { ... };
}

我们有2个工作线程,它们持有对Master类运行对象的引用同时。在他们的工作中,他们都必须访问master.foo的方法。在某些时候,master的Foo对象将被其中一个工作线程更改。现在我的问题是:使用volatile会使整个构造线程安全吗?我问这个是因为在来自Oracle的Java教程中,它说

We have 2 worker threads which hold a reference to an object of class Master running at the same time. During their work, both have to access methods of master.foo. At some point, the Foo object of master will be changed by one of the worker threads. Now my question: Does the use of volatile make the whole construction thread-safe? I am asking this because in a Java tutorial from Oracle it says


但是,您可以指定原子的动作:

However, there are actions you can specify that are atomic:


  • 读取和写入对于引用变量是原子的[...]

原子操作不能交错,因此它们是可以使用而不用担心线程干扰。

Atomic actions cannot be interleaved, so they can be used without fear of thread interference.

我只是想确保我理解正确。

I just would like to make sure that I understood this correctly.

提前致谢:)

推荐答案

在Java中读取和写入引用始终是原子的因此,没有危险,例如,在一些半更新状态下看到引用。如果你的意思是线程安全,则操作是线程安全的,有或没有关键字。

Reads and writes of references are always atomic in Java, so there is no danger of, for example, seeing the reference in some half-updated state. If this is what you mean by "thread safe" then the operation is thread safe with or without the keyword.

但是 volatile 与原子性无关,它会影响线程是否可以在本地缓存写入。 volatile 会强制写入写回主内存并对其他线程可见。如果你的意思是线程安全,那么是的,你需要这个关键字。

But volatile is not about atomicity, it affects whether threads can cache writes locally. volatile would force writes to be written back to main memory and be visible to other threads. If that is what you mean by thread-safe, then yes you need this keyword.

volatile 本身不是影响方法是否调用 foo 是否排除其他线程。如果你的意思是你想要使用 synchronized ,并且在另一个地方。

volatile itself does not affect whether method calls on foo exclude other threads or not. If that's what you mean you want to use synchronized, and in a different place.

这篇关于Java:volatile足以使类线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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