1 public class StopThread { 2 3 private static boolean stopRequested; 4 5 public static void main(String[] args) throws InterruptedException { 6 7 Thread thread = new Thread(new Runnable() { 8 @Override 9 public void run() { 10 int i = 0; 11 while (!stopRequested) { 12 i++; 13 } 14 } 15 }); 16 thread.start(); 17 TimeUnit.SECONDS.sleep(1); 18 stopRequested = true; 19 20 } 21 }
这是原书的代码,在我电脑上线程会一直运行,
但是在循环中添加打印代码,就会在一秒后退出循环
比如
public class StopThread { private static boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (!stopRequested) { i++; System.out.println("i=" + i); } } }); thread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; } }
请问大神这是为什么?是什么造成的这种影响?
因为输出那块有次强同步(println内部有个synchronized),这样导致cpu cache也失效,也就会导致第二个例子线程会退出。
谢谢大神