gpt4 book ai didi

java - 线程在从空 DataInputStream 读取 UTF 时卡住

转载 作者:行者123 更新时间:2023-11-30 04:48:41 25 4
gpt4 key购买 nike

只有一个线程正在创建。在某些情况下需要将其关闭。在这种情况下,可以通过检查 isInterrupted() 来完成。但如果输入流为空,它会卡住在 in.readUTF() 上。如何解决这个问题?

DataInputStream in;
....
public void stop() {
thread.interrupt();
}

public void run() {
    while(true) {
          String str = in.readUTF();  // locking here, when stream is empty
          S.o.p(str)
          if(isInterrupted) {
          return;
       }}
}

public void main(String args[]) {
     Thread thread = new Thread();      
}

最佳答案

您无法中断阻塞的输入流。 (这是与 NIO 的区别之一)您可以在调用中断之前关闭流,这将触发 IOException。

public void stop() {
in.close(); // or use something like IOUtils.closeQuietly(in);
thread.interrupt();
}

关于java - 线程在从空 DataInputStream 读取 UTF 时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com