Demo:
/**
* @author NanShan @create
* 2020-08-27 19:50
*
* Note:
* 1.程序并不能正常退出
* 2.修改方法:volatile boolean flag = true;
* 3.疑问:为什么在run方法中打印一个东西,程序就能正常退出?
*/
public class Main extends Thread {
boolean flag = true;
@Override
public void run() {
while (flag) {
}
}
public static void main(String[] args) throws Exception{
Main test = new Main();
test.start();
TimeUnit.SECONDS.sleep(5);
test.flag = false;
System.out.println("Flag已置空...");
}
}