【发布时间】:2015-07-28 04:03:41
【问题描述】:
public class Volatile {
volatile int x = 0;
public static void main(String a[]) {
Volatile y = new Volatile();
test t1 = new test(y);
test t2 = new test(y);
t1.setName("A");
t2.setName("B");
t1.start();
t2.start();
}
}
class test extends Thread {
Volatile v;
test(Volatile v) {
this.v = v;
}
@Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(Thread.currentThread().getName() + "Says Before " + v.x);
v.x++;
System.out.println(Thread.currentThread().getName() + "Says After " + v.x);
}
}
}
输出
ASays Before 0
BSays Before 0
BSays After 2
BSays Before 2
BSays After 3
ASays After 1 <--- Is it a cache value ?
BSays Before 3
ASays Before 3
BSays After 4
BSays Before 5
BSays After 6
ASays After 5 <--- Is it a cache value ?
ASays Before 6
ASays After 7
ASays Before 7
ASays After 8
到处,我发现了关于 volatile 的共同点
保证它不会被缓存并且不同的线程 将看到更新后的值
但是,从我上面的例子来看,线程有不同的值(旧/缓存值)还是因为不正确的实现?
【问题讨论】:
-
你看过Atomic Access吗?
-
@MadProgrammer 它说对 volatile 变量的更改始终对其他线程可见
-
是的,确实如此,但问题仍然是这些更改何时真正提交......
-
@MadProgrammer 你的意思是,我们永远无法确定增量是否完成。我对吗 ?如果是这样,那么我们永远无法预测多线程环境中的 volatile 变量值。对吗?
-
差不多,链接的答案对此有一些有趣的观点,因此您可以同时使用
synchronized和volatile或使用AtomicAPI,它为您提供了一些其他选项跨度>
标签: java multithreading volatile