简体   繁体   中英

InputStream reader blocking thread

I wrote this InputStream reader to listen to a Socket. This code is in a while(!stop) loop inside the run method of a thread. This reader blocks the thread, and does not print the message.

int read = 0;
byte[] buf = new byte[512];
int index = 0;
try {
    while (!stop && (read = in.read()) != -1) {
        System.out.println("read loop");
        buf[index++] = (byte) read;
    }
} catch (IOException e) {
    e.printStackTrace();
}

The read indeed blocks the thread running if no data is available.

What you want is to read a byte with a timeout ?

Look for answer to this in Is it possible to read from a InputStream with a timeout?

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