[英]How I can put a lock around InputStream and release when reading is done
I want to put a Lock around java.io.InputStream
Object and lock this stream. 我想在
java.io.InputStream
对象周围放置一个Lock并锁定此流。 And when I am done finished reading I want to release the lock. 当我完成阅读后,我想释放锁。 How can I achieve this?
我该如何实现?
Do you mean? 你的意思是?
InputStream is =
synchronized(is) { // obtains lock
// read is
} // release lock
Its usually a good idea to use one thread to read or write to a stream, otherwise you are likely to get some confusing and random bugs. 使用一个线程读取或写入流通常是一个好主意,否则您可能会遇到一些令人困惑的随机错误。 ;)
;)
If you want to use a Lock as well 如果您也想使用锁
InputStream is =
Lock lockForIs =
lockForIs.lock();
try {
// read is
} finally {
lockForIs.unlock();
}
You can't just lock on the InputStream, as it wouldn't prevent write access from a relevant OutputStream; 您不能只锁定InputStream,因为它不会阻止来自相关OutputStream的写访问; you have to check the lock any time you want to write from the OutputStream.
您必须在要从OutputStream写入的任何时间检查锁定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.