Interrumpa un hilo esperando la entrada del usuario y luego salga de la aplicación
Tengo dos hilos en ejecución,userInputThread
espera la entrada del usuario desde la línea de comando yinterrupterThread
intenta interrumpiruserInputThread
1 segundo después de comenzar. Obviamente no puedes interrumpir un hilo que está bloqueado por elSystem.in
. Otra respuesta sugiere cerrar.System.in
conSystem.in.close()
Antes de interrumpir un hilo. Pero cuando ejecuto el siguiente código, eluserInputThread
Nunca se interrumpe y la aplicación simplemente se cuelga sin cerrarse.
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();
}
}
Ya hay un similarpregunta, pero no hay respuestas definitivas.