如何知道BufferedReader Stream是否已关闭 [英] How to know if a BufferedReader Stream is closed

查看:608
本文介绍了如何知道BufferedReader Stream是否已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有两个线程。

I have two threads in Java.

第一个线程正在关闭一个bufferedreader( br.close()

First thread is closing a bufferedreader (br.close())

当第二个线程在同一个阅读器上读取时,我得到一个 IOException(Stream Closed)

When the second thread does a read on the same reader I get an IOException (Stream Closed)

即使我使用 br.ready()

有没有办法知道流是否已经关闭?

Is there a way to know if the stream is already closed?

推荐答案

方法 ready()将在关闭时抛出异常。但即使您添加了一个封闭的检查方法,只要在调用之间释放锁定(对于 BufferedReader ),读者可能会在您阅读时关闭它。

The method ready() will throw an exception if closed. But even if you added a closed check method, so long as the lock is released between calls (which it is for BufferedReader), the reader might be closed by the time you read it.

我看到三个选项:


  1. 用一个包裹你的来电try / catch块来处理已关闭的案例。

  2. 创建 BufferedReader 的子类,扩展 close() 设置你自己的变量,可以用
    检查阅读器是否关闭。这还需要覆盖很多
    方法来执行你想要的关闭阅读器的任何行为,如果你想要它做什么除了抛出 IOException

  3. 添加一个你自己的锁并用它来关闭阅读器(一个线程)和
    检查缓冲区是否准备就绪并从中读取。您可以直接为检查设置变量,也可以将 ready() read()调用分组相同的同步块。

  1. Wrap your read call with a try/catch block to handle the closed case.
  2. Create a subclass of BufferedReader that extends close() to set your own variable that can be used to check to see if the reader is closed. This also requires overriding a lot of methods to do whatever the behavior you want with a closed reader if you want it do something beside throw the IOException.
  3. Add a lock of your own and use it to both close the reader (one thread) and check that the buffer is ready and read from it. You can either set a variable directly for the check or just group the ready() and read() calls into the same synchronized block.

这篇关于如何知道BufferedReader Stream是否已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆