Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...