Running this code, I would expect it to increment the test variable for 5 seconds and then finish.
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 );
}
}
However when I run it the program doesn't end (I assume, I have given it a reasonable amount of time). However if I change the while loop to
while( running ) {
System.out.println();
test++;
}
The program finishes in the expected amount of time (and prints out a lot of lines). I don't understand. Why does this behaviour occur?