我有兩個線程在運行,userInputThread
等待用戶從命令行輸入,interrupterThread
在啓動後1秒鐘嘗試中斷userInputThread
。顯然,您不能中斷System.in
阻止的線程。另一個答案建議在中斷線程之前用System.in.close()
關閉System.in
。但是,當我運行以下代碼時,userInputThread
永遠不會中斷,應用程序只是掛起而不關閉。中斷等待用戶輸入的線程,然後退出應用程序
class InputInterruptionExample {
private Thread userInputThread;
private Thread interrupterThread;
InputInterruptionExample() {
this.userInputThread = new Thread(new UserInputThread());
this.interrupterThread = new Thread(new InterrupterThread());
}
void startThreads() {
this.userInputThread.start();
this.interrupterThread.start();
}
private class UserInputThread implements Runnable {
public void run() {
try {
System.out.println("enter your name: ");
String userInput = (new BufferedReader(new InputStreamReader(System.in))).readLine();
} catch (IOException e) {
System.out.println("Oops..somethign went wrong.");
System.exit(1);
}
}
}
private class InterrupterThread implements Runnable {
public void run() {
try {
sleep(1000);
System.out.println("about to interrupt UserInputThread");
System.in.close();
userInputThread.interrupt();
userInputThread.join();
System.out.println("Successfully interrupted");
} catch (InterruptedException e) {
} catch (IOException ex) {
System.out.println("Oops..somethign went wrong.");
System.exit(1);
}
}
}
public static void main(String[] args) {
InputInterruptionExample exampleApp = new InputInterruptionExample();
exampleApp.startThreads();
}
}
不過已經有了類似的question,但目前還沒有任何明確的答案。
非常酷。通過關閉流強制NPE。先生+1。 – claymore1977
我認爲它也適用於closeBufferdReader – user1121883
@ user1121883你是對的。出於某種原因,我認爲你不能中斷()System.in阻塞的線程。嗯... – Sbbs