【发布时间】:2014-02-01 23:05:45
【问题描述】:
我有一个同时运行的程序,我遇到了这个问题,我想停止线程,但是一旦我点击进入,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 循环会导致程序不关闭?
【问题讨论】:
-
顺便说一句,它不应该说 while(processing == true),而只是 while(processing)。此外,由于调用 permSleep 方法导致变量处理 == false,因此在控制台中输入某些内容后,while 循环是否不会中断?
-
这将无限期地每秒打印一次“字母 i”。
标签: java multithreading loops