如何知道BufferedReader Stream是否已关闭 [英] How to know if a BufferedReader Stream is closed
问题描述
我在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.
我看到三个选项:
- 用一个包裹你的来电try / catch块来处理已关闭的案例。
- 创建
BufferedReader
的子类,扩展close()
设置你自己的变量,可以用
检查阅读器是否关闭。这还需要覆盖很多
方法来执行你想要的关闭阅读器的任何行为,如果你想要它做什么除了抛出IOException
。 - 添加一个你自己的锁并用它来关闭阅读器(一个线程)和
检查缓冲区是否准备就绪并从中读取。您可以直接为检查设置变量,也可以将ready()
和read()
调用分组相同的同步块。
- Wrap your read call with a try/catch block to handle the closed case.
- Create a subclass of
BufferedReader
that extendsclose()
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 theIOException
. - 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()
andread()
calls into the same synchronized block.
这篇关于如何知道BufferedReader Stream是否已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!