简体   繁体   English

停止从 readLine() 方法读取被阻止的线程

[英]Stop Thread that is blocked reading from a readLine() method

while (active) {
   String message = reader.readLine();
}


public void stop(){
   active = false;
}

How do i stop this Thread before readLine() return a String ?如何在readLine()返回String之前停止此Thread

As you've likely identified, your boolean check is all well and good, but doesn't work if your thread blocks on network I/O, or is sleeping.正如您可能已经确定的那样,您的布尔检查一切正常,但如果您的线程在网络 I/O 上阻塞或正在休眠,则它不起作用。 Instead you need to interrupt this thread.相反,您需要中断此线程。 See here for more details.请参阅此处了解更多详情。

In this case, your BufferedReader has to be closed to unblock the reading thread.在这种情况下,必须关闭 BufferedReader 以解除对读取线程的阻塞。

public void stop() {
    closeQuietly(reader); // unblock
    active = false;
}

public static void closeQuietly(Closable c) {
    if(c != null)
        try {
            c.close();
        } catch(IOException ignored) { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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