我正在用 Threads 打破一些僵局,但我被卡住了,因为
pressing RETURN key thread ends
但是在输入一些字符串
时,线程没有停止
。为什么会这样,因为 nexLine()
方法接受任何字符串值,为什么按 RETURN 键线程会停止?
class MyThread extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.println("hello");
}
}
public void shutdown() {
running = false;
}
}
public class Main {
public static void main(String[] args) {
MyThread obj = new MyThread();
obj.start();
Scanner input = new Scanner(System.in);
input.nextLine();
obj.shutdown();
}
}
最佳答案
它在到达行尾的那一刻就停止了。输入“enter”与点击“\n”相同,从而停止。阅读有关该方法和 Scanner 类的文档可能有助于进一步理解它。
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
关于java - Scanner 的 nextLine() 方法如何在按返回键时停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494788/