java 是否可以同时读取和写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3966229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to read and write in file at the same time?
提问by mohamida
Here's the scenario:
这是场景:
- ThreadA is going to read from some socket, and write data to "MyFile.txt"
- ThreadB is going to read "MyFile", and when it reaches the end, it will loops until new data are available in MyFile (because i don't want to re-open "MyFile.txt", and lose the time so i reach the position from where i was..).
- ThreadA 将从某个套接字读取,并将数据写入“MyFile.txt”
- ThreadB 将读取“MyFile”,当它到达末尾时,它将循环直到 MyFile 中有新数据可用(因为我不想重新打开“MyFile.txt”,并且浪费时间所以我到达我所在的位置......)。
Is it possible to do such a thing ?
有可能做这样的事情吗?
If not, is there another way to do such a thing ?
如果没有,还有另一种方法可以做这样的事情吗?
回答by Cheok Yan Cheng
The problem you mention is a famous Producer Consumer Problem
你提到的问题是著名的生产者消费者问题
Common solution to this is to use BlockingQueue
对此的常见解决方案是使用BlockingQueue
An example of real world usage is in AjaxYahooSearchEngineMonitor
AjaxYahooSearchEngineMonitor是真实世界使用的一个例子
What Thread A does is, it will submit a string to queue, and then return immediately.
线程A所做的是,它会向队列提交一个字符串,然后立即返回。
What Thread B does is, it will pick up the item from queue one by one, and process them. When there is no item in the queue, Thread B will just wait there. See line 83 of the source code.
线程B所做的就是,它会从队列中一个一个地取出项目,并对其进行处理。当队列中没有项目时,线程 B 将在那里等待。请参阅源代码的第 83 行。