可能重复:
静态全局变量和静态易失变量有什么区别?
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 才能达到目的吗?