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

后端 未结 7 1904
萌比男神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
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题