-2
可能重複的:
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才能達到目的?