简体   繁体   中英

How to interrupt a read operation using BufferedReader (Java)?

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.

You could check to see if there's data available before calling BufferedReader.readLine() , ie

while(true) {
    if (!listening) break;
    if (System.in.available() > 0) {
        try {
            fromUser = stdIn.readLine();
            // etc.

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

我想你可以使用 stdIn.close() 关闭你的 BufferedReader;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM