我已经读过Java中的"volatile"允许不同的线程访问同一个字段并查看其他线程对该字段所做的更改.如果是这种情况,我预测当第一个和第二个线程完全运行时,"d"的值将增加到4.但是,每个线程将"d"增加到值2.
public class VolatileExample extends Thread {
private int countDown = 2;
private volatile int d = 0;
public VolatileExample(String name) {
super(name);
start();
}
public String toString() {
return super.getName() + ": countDown " + countDown;
}
public void run() {
while(true) {
d = d + 1;
System.out.println(this + ". Value of d is " + d);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new VolatileExample("first thread");
new VolatileExample("second thread");
}
}
Run Code Online (Sandbox Code Playgroud)
运行此程序的结果是: …