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

后端 未结 7 1906
萌比男神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:14

    I had the same problem today, and this is how I fixed it, using in.ready() :

    public void run() {
        String line;
        // Some code
    
        while(!Thread.currentThread().isInterrupted()){
            try {
                if (in.ready()) {
                    line = in.readLine();
                } 
            } catch (Exception e) {
                try {
                    Thread.currentThread().wait(500);
                } catch (InterruptedException e1) {
                    // Do what we want when thread is interrupted
                }
            }
        }
    }
    

提交回复
热议问题