Java:有正确的方法来使用静态volatile变量吗? [英] Java: Is there a right way to use static volatile variables?

查看:177
本文介绍了Java:有正确的方法来使用静态volatile变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个标志,可以访问从不同的线程读/写,没有任何脏值的问题。是否足以使其变为静态变量?

I want to have a flag that could be accessible to read/write from different threads without any problem of dirty values. Is it enough to make it static volatile?

static volatile boolean flag;


推荐答案

不,这是不够的,如果你需要一个动作像这样:

No, this is not enough if you need an action like this:

volatile int v = 0;

Thread 1:
v++;

Thread 2:
v--;

理想情况下,当您执行上述代码时,您希望v = 0,但这是真正发生的事情复合动作):

Ideally you want v=0 when you execute the above code, but this is what is really happening (a composite action):

Thread 1:
r1 = v;
r2 = r1 + 1;
v = r2;

Thread 2:
r3 = v;
r4 = r3 - 1;
v = r4;

这两个线程分别给出值1和-1。资料来源:挥发性不意味着原子!

And both the threads will give values of 1 and -1 respectively. Source: Volatile Does Not Mean Atomic!

如果你需要在多线程场景中保证一致的结果,你应该使用Java中的Atomic类,正如@ Eng.Fouad指出的那样。

If you need guaranteed consistent result in a mulithreaded scenario, you should be using Atomic classes in Java as @Eng.Fouad pointed out.

在布尔值的情况下,compare-and-set将比使用volatile有利于AtomicBoolean类。

In the case of a boolean too, compare-and-set will be helpful from AtomicBoolean class than using volatile.

这篇关于Java:有正确的方法来使用静态volatile变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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