【发布时间】:2015-06-03 03:26:28
【问题描述】:
我正在尝试编写一个简单的代码来理解 java 中的 volatile 关键字。
这个想法是使用两个线程来增加 Runner 类的 count 字段的值。 Helper 类实现了 Runnable,其中 run 方法增加 static 和 volatile 的 count。
class Helper implements Runnable{
@Override
public void run() {
for(int i=0; i<100000;i++){
Runner.count+=1;
}
}
}
public class Runner {
public static volatile long count=0; // to be incremented
public static void main(String[] args){
Thread t1 = new Thread( new Helper());
Thread t2 = new Thread( new Helper());
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count= "+count); // output expected to be 200000
}
}
每次运行的预期输出是 Count= 200000 ,但有时我会得到不同的数字。 请帮助我了解这怎么可能
【问题讨论】:
-
Volatile 提供可见性,但不提供原子性(这是诸如变量增量之类的复合操作所需要的)。
标签: java multithreading volatile