Is it possible to read and write to a file at the same time?

Here's the script:

  • 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 cycle until new data appears in MyFile (because I don’t want to re-open “MyFile.txt” and lose time so I get to where I was. .).

Can this be done?

If not, is there any other way to do such a thing?

+7
java multithreading file-io
source share
2 answers

The issue you mentioned is a known issue from the manufacturer

A common solution for this is to use BlockingQueue

Real-world example in AjaxYahooSearchEngineMonitor

What Thread A is, it will send the line to the queue and then immediately return.

What is Thread B, it will collect the element from the 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.

+13
source share

I think you can use java nava libraries

+2
source share

All Articles