I am now reading 《effective Java》 and meeting a confusion.
For code 1 (java8) :
public class StopThreadTest {
private static Boolean stopRequest = false;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i = 0;
while (!stopRequest) {
i++;
//System.out.println("i: " + i);
}
}).start();
TimeUnit.SECONDS.sleep(1);
stopRequest = true;
}
}
the program never terminates.
For code 2(java8):
public class StopThreadTest {
private static Boolean stopRequest = false;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i = 0;
while (!stopRequest) {
i++;
System.out.println("i: " + i);
}
}).start();
TimeUnit.SECONDS.sleep(1);
stopRequest = true;
}
}
Just adding System.out.println()
, the program run about 1 second.
Can anybody tell me why?