简体   繁体   English

是否可以同时读写文件?

[英]Is it possible to read and write in file at the same time?

Here's the scenario: 这是场景:

  • ThreadA is going to read from some socket, and write data to "MyFile.txt" ThreadA将要从某些套接字读取,并将数据写入“ 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..). ThreadB将读取“ MyFile”,到达末尾时它将循环播放,直到MyFile中有新数据可用为止(因为我不想重新打开“ MyFile.txt”,并且浪费时间,所以我到达了从我所在的位置..)。

Is it possible to do such a thing ? 可以做这样的事情吗?

If not, is there another way to do such a thing ? 如果没有,还有其他方法可以做这种事情吗?

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. 线程B所做的是,它将从队列中一个接一个地拿起物品,并对其进行处理。 When there is no item in the queue, Thread B will just wait there. 当队列中没有项目时,线程B将在那里等待。 See line 83 of the source code. 参见源代码的第83行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM