while循環中使用輸出語句停止死循環的原因
直接看代碼
public class WhileTest { private boolean flag = true; public void setFlag(boolean flag) { this.flag = flag; } public void say() { while(flag) { } System.out.println("--------------線程停止------------------------------------"); } public static void main(String[] args) throws InterruptedException { final WhileTest wt = new WhileTest(); Thread t = new Thread(new Runnable() { @Override public void run() { wt.say(); } }); t.start(); Thread.currentThread().sleep(500); wt.setFlag(false); } }
public void say() { while(flag) { System.out.println(""); } System.out.println("--------------線程停止------------------------------------"); }
public void println(String x) { synchronized (this) { print(x); newLine(); } }
很明顯,會出現死循環,因為主線程修改共享變量的值,另一個線程並且讀取到修改
常見的解決方案是
flag 加上volatile關鍵字,強制刷新共享變量的值和主內存的值一致。
但是,如果在while循環體中加上一段輸出語句,也能夠停止線程,原因在哪里,看下源碼
-
果while循環內,加上Thread.sleep語句,給CPU一段時間,cpu會去同步主內存和工作內存的共享變量的值,也能夠停止死循環,不過不推薦這樣實現,存在不確定性。