简体   繁体   中英

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"
  • 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..).

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

An example of real world usage is in AjaxYahooSearchEngineMonitor

What Thread A does is, it will submit a string to queue, and then return immediately.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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