我有一个同时运行一个程序,我有这个问题,我想停止线程,但for循环/ while循环没有被取消,一旦我一次,我点击进入For和While循环
如果我取出while
循环中的for
循环,程序实际上响应输入并关闭。
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
循环导致程序不关机?
顺便说一句,它不应该说(虽然处理==真),而只是while(处理)。此外,while循环不会因为调用使得变量处理== false而使用的permSleep方法而在控制台中输入某些内容而中断? – JavaNewb
无限期地,每秒打印一次“Letter i”。 –