运行此代码,我期望它会在5秒钟内增加测试变量,然后结束。
然而,当我运行它时,程序并没有结束(我认为我已经给了它足够的时间)。但是,如果我将 while 循环改为:
import java.util.Timer;
import java.util.TimerTask;
public class Test {
private static boolean running;
public static void main( String[] args ) {
long time = 5 * 1000; // converts time to milliseconds
long test = Long.MIN_VALUE;
running = true;
// Uses an anonymous class to set the running variable to false
Timer timer = new Timer();
timer.schedule( new TimerTask() {
@Override
public void run() { running = false; }
}, time );
while( running ) {
test++;
}
timer.cancel();
System.out.println( test );
}
}
然而,当我运行它时,程序并没有结束(我认为我已经给了它足够的时间)。但是,如果我将 while 循环改为:
while( running ) {
System.out.println();
test++;
}
程序在预期的时间内完成(并输出了大量的行)。我不明白,为什么会发生这种行为?
volatile
会怎样? - Andy Turner