java - 在线程上设置中断标志

标签 java multithreading

对于下面的代码,

static class SleeperThread  extends Thread {
  public void run() {
    int c;
    try {
        c = System.in.read();
    }
    ...
  }
}

正如本文中提到的bug ,如果一个线程在 IO(System.in.read();) 上被阻塞,那么,不能由另一个线程在该线程上设置中断标志吗?

最佳答案

由于 System.in 不对线程中断使用react,因此您必须自己实现类似的东西。

为此,您可以使用 System.in(InputStream)的 available() 方法。

它可能看起来有点像这样:

class ReadWithInterrupt extends Thread{
    private byte[] result = null;
    public byte[] getResult(){
        return result;
    }

    @Override
    public void run(){
        try{
            while(true){
                if (this.isInterrupted()){
                    System.out.println("An interrupt occurred");
                    break;
                }
                int available = System.in.available();
                if (available>0){
                    result = new byte[available];
                    System.in.read(result, 0, available);
                    break;
                }
                else
                    Thread.sleep(500);
            }

        }
        catch (IOException e){
            e.printStackTrace();
        }
        catch (InterruptedException e){
            System.out.println("An interrupt occurred");
        }
    }
}

关于java - 在线程上设置中断标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593756/

相关文章:

java - Eclipse 未找到可执行 Jar 的库

c# - task.delay 执行后是否有无限代码?

c# - 连续发出多个 Web 请求的最简单方法是什么?

multithreading - Chdir 和Setuid 以及Setgid 线程安全吗?

java - Swing 中的堆栈面板

java - 在 JTree 中获取一个节点

Delphi - 当应用程序退出时,未释放(但终止)的线程会发生什么?

multithreading - Ocaml:有没有办法在进程之间传递对象?

java - WebDriverException : java.net.ConnectException:无法在 MacOS 上使用 Selenium 3 和 chromedriver 连接到本地主机错误

java - 如何将 JPA OneToMany 关系转换为 DTO