How to stop a thread waiting in a blocking read operation in Java?

后端 未结 7 1917
萌比男神i
萌比男神i 2020-12-03 10:40

I have a thread that executes the following code:

public void run() {
    try {
        int n = 0;
        byte[] buffer = new byte[4096];
        while ((n          


        
7条回答
  •  悲哀的现实
    2020-12-03 11:10

    You could use the available() method (which is non-blocking) to check whether there is anything to read beforehand.

    In pseudo-java:

    //...
    while(running)
    {
        if(in.available() > 0)
        {
            n = in.read(buffer);
            //do stuff with the buffer
        }
        else
        {
            Thread.sleep(500);
        }
    }
    //when running set to false exit gracefully here...
    

提交回复
热议问题