可能重复:
What is the difference between a static global and static volatile variable?
public class Test {
volatile boolean running = true;
public void count() {
new Thread(new Runnable() {
public void run() {
int counter = 0;
while (running) {
counter++;
System.out.println("Thread 1 counting " + counter);
}
System.out.println("Thread 1 finished. Counted up to "
+ counter);
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException ignored) {
}
System.out.println("Thread 2 finishing");
running = false;
}
}).start();
}
public static void main(String[] args) {
new Test().count();
}
}
我没有发现静态变量和volatile变量之间存在差异?
在上面的代码中我也可以用静态变量实现同样的事情,任何机构都可以举例说明只有volatile才能达到目的吗?
答案 0 :(得分:0)
第一个出现在我脑海中的人:
http://www.docjar.com/html/api/java/util/concurrent/atomic/AtomicLong.java.html
在值上使用volatile来强制更新的原子性。