简体   繁体   English

读完后如何锁定InputStream并释放

[英]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.

相关问题 如何提高读取 InputStream 的性能? - How can I increase performance on reading the InputStream? 如何在任务完成之前不返回HttpURLConnection InputStream? - How can I not return HttpURLConnection InputStream before task is done? 如何在不读取的情况下检查 InputStream 是否为空? - How can I check if an InputStream is empty without reading from it? 我如何gzip一个InputStream并返回一个InputStream? - How can I gzip an InputStream and return an InputStream? InputStream包装器,读取完成后将关闭流 - InputStream wrapper that closes the stream once reading is done 如何使方法 isEmpty() 为真,以便我最终可以从 InputStream 读取数据? - How to make the method isEmpty() true so that I can end up reading data from InputStream? 如何有效地将未压缩的InputStream转换为gzip的InputStream? - How can I convert an uncompressed InputStream into a gzip'ed InputStream efficiently? 当我使用输入流阅读器时,我无法在从缓冲阅读器读取数据后退出 while 循环 - when i used inputstream reader i can't exit from the while loop after reading the data from the buffered reader 我可以锁定DB2的行以进行读取吗? - Can I lock row of DB2 for reading? 读取文件作为输入流时如何获取Excel文件名 - How to get Excel file name when reading the file as inputstream
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM