我有一个程序在同时运行,但是我遇到了这样一个问题:当我想要停止线程时,for循环/while循环并没有被取消,一旦我点击回车键。
如果我将for循环从while循环中拿出来,程序实际上会响应回车键并关闭。
为什么使用
如果我将for循环从while循环中拿出来,程序实际上会响应回车键并关闭。
class MyNumber extends Thread {
private volatile boolean processing = true;
public void run() {
while (processing) {
// Once I take this for loop out(put // beside it like right now), the enter key to stop the program then does work.
//for(int i = 1; i<27; i++){
System.out.println("Letter " + "i");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// }
}
}
public void permSleep() {
processing = false;
}
}
public class LetterNumber {
public static void main(String[] args) {
MyNumber num1 = new MyNumber();
num1.start();
System.out.println("Hit enter to stop the Numbers!");
Scanner shutter1 = new Scanner(System.in);
shutter1.nextLine();
num1.permSleep();
}
}
为什么使用
for
循环会导致程序不关闭?