这样就解决了问题:
class InputInterruptionExample {
private UserInputThread userInputRunnable;
private Thread userInputThread;
private Thread interrupterThread;
InputInterruptionExample() {
this.userInputRunnable = new UserInputThread();
this.userInputThread = new Thread(userInputRunnable);
this.interrupterThread = new Thread(new InterrupterThread());
}
void startThreads() {
this.userInputThread.start();
this.interrupterThread.start();
}
private class UserInputThread implements Runnable {
private InputStreamReader isr;
private BufferedReader br;
UserInputThread() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
}
public void run() {
try {
System.out.println("enter your name: ");
try{
String userInput = br.readLine();
} catch(NullPointerException e) {}
} catch (IOException e) {
System.out.println("Oops..somethign went wrong.");
System.exit(1);
}
}
public void closeBufferdReader() {
try {
System.in.close();
} catch (IOException e) {
System.out.println("Oops..somethign went wrong in closeBufferdReader() method");
System.exit(1);
}
}
}
private class InterrupterThread implements Runnable {
public void run() {
try {
sleep(1000);
userInputRunnable.closeBufferdReader();
userInputThread.interrupt();
userInputThread.join();
System.out.println("Successfully interrupted");
} catch (InterruptedException e) {}
}
}
public static void main(String[] args) {
InputInterruptionExample exampleApp = new InputInterruptionExample();
exampleApp.startThreads();
}
}
更新:仅当以这种方式拆分BufferedReader时,此方法才有效:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String userInput = br.readLine();
由于某些原因,当将readLine()结构编写为单行时,中断似乎不起作用:
this.userInput = (new BufferedReader(new InputStreamReader(System.in))).readLine();
因此,尽管可以中断拆分后的BufferedReader结构中的线程,但现在无法读取用户的输入.
如果有人能够显示出一种能够获取用户输入并在用户未及时提供任何输入(中断器处于睡眠状态时)中断UserInputThread的方法,请执行此操作.