簡體   English   中英

停止從 readLine() 方法讀取被阻止的線程

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

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


public void stop(){
   active = false;
}

如何在readLine()返回String之前停止此Thread

正如您可能已經確定的那樣,您的布爾檢查一切正常,但如果您的線程在網絡 I/O 上阻塞或正在休眠,則它不起作用。 相反,您需要中斷此線程。 請參閱此處了解更多詳情。

在這種情況下,必須關閉 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