Reputation: 19366
Hello although I read a lot of other answeres I do not understand how to close BufferedReader without sending input. This is the blocking part of my program:
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;
}
}
When I call "endListening()" from the main thread, the program terminates - but NOT BEFORE the user inputs anything. I want to the program to terminate instantly - how to intterupt this BufferdReader (is created like BufferedReader(new InputStreamReader(System.in)) )?
I tried to call stdIn.close() and also thread.interrupt() on this Thread in the main Thread, but it ist not working. I also tried to close the InputStreamReader in the main Thread.
Upvotes: 1
Views: 2661
Reputation: 32323
You could check to see if there's data available before calling BufferedReader.readLine()
, i.e.
while(true) {
if (!listening) break;
if (System.in.available() > 0) {
try {
fromUser = stdIn.readLine();
// etc.
Upvotes: 1
Reputation: 24780
You must use thread.interrupt
to signal the thread to interrupt its process. Be ready to catch an InterruptedException
launched by the thread.
http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
Upvotes: 1