java - InputStream - 关闭、中断阻塞 read()

标签 java netbeans concurrency io

一些输入-输出对象,如InputStream,在读、写过程中不能中断,也不能关闭源。

例子:

class InputStreamOperation1 implements Runnable
{
    static InputStream stream;

    InputStreamOperation1(InputStream stream) { this.stream = stream; }

    public void run()
    {
        System.out.println("InputStreamOperation - the beginning");
        try
        {
            stream.read(); //blocking operation
        } catch (Exception e)
        {
            System.out.println("InputStreamOperation interrupted");
        }
        System.out.println("InputStreamOperation - the end");
    }
}

试图打断:

ExecutorService executor = Executors.newCachedThreadPool();
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting InputStream");
f.cancel(true); // Interrupts if running
System.out.println("Interrupt sent to InputStream");

正在尝试关闭源

Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Closing source in InpuStream");
try
{
      System.in.close();
} catch (IOException e)
{
      System.out.println("Error during closing InputStreamOperation");
}
System.out.println("Closed source in InputStream");

两种解决方案均无效。它会在至少阅读一封信后中断或关闭。

我的问题:有什么方法可以中断阻塞的 read() 操作或在此阻塞操作期间关闭源代码?

我在这里找到了类似的东西 - Is it possible to read from a InputStream with a timeout? .我想知道是否有任何其他解决方案(尤其是中断或关闭源)来停止线程,或者唯一的解决方案与这种棘手的方式有关。

最佳答案

Both solutions are not working. It interrupts or closes after reading at least one letter.

我可以关闭 System.in

我的输出显示:

InputStreamOperation - the beginning
Closing source in InpuStream
Closed source in InputStream
read: -1
InputStreamOperation - the end

我添加了读取结果的打印,当我在另一个线程中关闭 System.in 时,它显示 -1 表示 EOF。

我想知道你的问题是不是你没有关闭你的ExecutorService?否则,您的申请将无法完成。

ExecutorService executor = Executors.newCachedThreadPool();
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
executor.shutdown();

如果它仍然不适合您,那么这一定是操作系统相关的。它适用于 OSX 和 Linux。

My question: it there any way to interrupt blocking read() operation or close the source during this blocking operation?

除了关闭一直对我有用的流之外,我知道的唯一其他方法是使用 NIO InterruptibleChannel 类并中断它。

编辑:

根据评论,您在 Netbeans 下工作,并且可能出于安全目的,网络包装器以某种方式保护了 System.in

关于java - InputStream - 关闭、中断阻塞 read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080699/

相关文章:

java - 为什么 HotSpot 会使用提升来优化以下内容?

java - 在构建 spring boot 应用程序时排除一些测试类

java - 是否可以使用 JFileChooser 限制特定目录可用的文件?

Java Servlet - 如何同步 ProcessBuilder?

database - 支持多个并发用户的文件数据库建议

sql - 防止 SQL 事务中的竞争条件以确保数据完整性

java - log4j 参数化日志记录

java - 为什么 DecimalFormat ".#"和 "0.#"在 23.0 上有不同的结果?

java - NetBeans 缺少项目类别

Netbeans 中的 C++ : many senseless "unexpected token" hints