<分区>
我看过Effective Java 2这本书第66条,里面说后台线程会一直运行,永不停止。但是当我在我的计算机中运行代码时,它会在一秒钟内停止?怎么了?是不是电脑缓存问题?
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested) {
i++;
System.out.println(i+";");
}
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
书上建议使用Synchronize
或volatile
,但我尝试发现即使我不使用该建议,它也会在我的计算机中运行一秒钟。但是在我的室友中永远奔跑。他说是缓存配置的原因。
谁能告诉我原因?