public class Test {
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++;
// if(i %10000 == 0) System.out.println(stopRequested + " in thread");
}
}
});
backgroundThread.start();
Thread.sleep(1000);
stopRequested = true;
System.out.println(stopRequested);
}
}
这段代码,会一直运行下去。
如果把注释的那行打开,就是下面这样,程序一秒后就停止,大神分析下为什么?
public class Test {
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++;
if(i %10000 == 0) System.out.println(stopRequested + " in thread");
}
}
});
backgroundThread.start();
Thread.sleep(1000);
stopRequested = true;
System.out.println(stopRequested);
}
}