<分区>
运行这段代码,我希望它会增加测试变量 5 秒,然后结束。
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++;
}
程序在预期的时间内完成(并打印出很多行)。我不明白。为什么会出现这种行为?