这个是书上的程序,会无限循环下去。public class Test {
private static boolean b;
private static int i = 1; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override
public void run() {
while (!b) {
System.out.println(i);
}
}
});
thread.start(); TimeUnit.SECONDS.sleep(1);
b = true;
i = 2;
System.out.println(b);
}
}这是我写的例子。会中止线程。

解决方案 »

  1.   

    要用server模式启动,此外去掉 System.out.println(),也就是尽量消除线程需要切换环境的可能性。应该就可以看到无限循环的效果了。
      

  2.   

    去了syso还是会中止。。server模式启动是啥意思哦。
      

  3.   


    倒不是Server模式启动,JVM是不会启用各种深度优化的,就看不到效果了;这是关键。Server模式启动,就是在 JVM 参数中增加 “-server”参数,如果你用Eclipse,可以从Run里面配置下。
      

  4.   


    客气,要能健康退出,变量加上 volatile 关键字。书中应该有写,呵呵。