这个是书上的程序,会无限循环下去。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);
}
}这是我写的例子。会中止线程。
倒不是Server模式启动,JVM是不会启用各种深度优化的,就看不到效果了;这是关键。Server模式启动,就是在 JVM 参数中增加 “-server”参数,如果你用Eclipse,可以从Run里面配置下。
客气,要能健康退出,变量加上 volatile 关键字。书中应该有写,呵呵。