eg:1
public class Test extends Thread {
private Boolean stop = false;
public static void main(String[] args) throws Exception {
Test test = new Test();
test.start();
TimeUnit.SECONDS.sleep(1);
test.stop = true;
}
@Override
public void run() {
while (!this.stop) {
}
System.out.println("end");
}
}
The code is written like this, and the thread will execute endlessly. However, add a little something to the while loop and change it to something like this:
eg:2
public class Test extends Thread {
private Boolean stop = false;
public static void main(String[] args) throws Exception {
Test test = new Test();
test.start();
TimeUnit.SECONDS.sleep(1);
test.stop = true;
}
@Override
public void run() {
while (!this.stop) {
System.out.println(1); // Add some code
}
System.out.println("end");
}
}
Q:
why is this happening? ??? Why can I interrupt it by printing a sentence, and it will not be interrupted without printing. . . . . . . . . . . . . . Note that stop
is not added volatile
. If added, it can be stopped after 1 second.