您好,虽然我阅读了很多其他答案,但我不明白如何在不发送输入的情况下关闭 BufferedReader。这是我程序的阻塞部分:
public class AuctionClientUserListener extends Thread {
private PrintWriter out;
private BufferedReader stdIn;
private int udpPort;
private boolean running = true;
private boolean listening = true;
// needs server connection out
public AuctionClientUserListener(BufferedReader stdIn,PrintWriter out,int udpPort) {
this.stdIn = stdIn;
this.out = out;
}
public void run() {
String fromUser;
while(true) {
if(!listening) {
break;
}
try {
fromUser = stdIn.readLine(); // BLOCKS
if (fromUser != null) {
System.out.println("Me: " + fromUser);
// check if to send udp port
String[] spinput = fromUser.split(" ");
if(spinput[0].equals("!login")) {
fromUser+=" "+udpPort;
}
out.println(fromUser);
if(fromUser.equals("!end")) {
listening = false;
}
}
} catch(Exception e) {
listening = false;
}
}
running = false;
}
public boolean running() {
return running;
}
public void endListening() {
this.listening = false;
}
}
当我从主线程调用“endListening()”时,程序终止——但不是在用户输入任何内容之前。我想让程序立即终止 - 如何中断这个 BufferdReader (像 BufferedReader(new InputStreamReader(System.in)) 一样创建)?
我试图在主线程的这个线程上调用 stdIn.close() 和 thread.interrupt(),但它不起作用。我还尝试关闭主线程中的 InputStreamReader。