3

我有一个事件处理方案,它最终也应该写入文件;我不能在文件被刷新时延迟事件,即等待 BufferedWriter.write(String) 结束。

我正在寻找实现这一目标的最简单方法(是否有图书馆这样做?我认为我不是唯一遇到此问题的人)

4

4 回答 4

5

您可以使用单线程执行器为每个事件执行文件写入。

ExecutorService executor = Executors.newSingleThreadExecutor();

// for each event
executor.submit(new Runnable() {
  public void run()
  {
     // write to the file here
  }
});

只有一个线程,执行程序将负责排队。

于 2009-05-06T09:39:49.147 回答
2

Basically, you want the writing to the file not interrupt your flow of event handling.

In this case, all you need to do is delegate the file handling away to a separate thread.

Your code should look something like this:

// event handling starts

Runnable fileHandlingThread = new Runnable() {
    public void run() {
        // open the file
        // write to the file
        // flush the file
    }
};

new Thread(fileHandlingThread).start();

// continue doing other things in the mean time
于 2009-05-06T08:29:48.877 回答
1

只要您保持相同的线程,您就可以使用它java.io.PipedOutputStream来存储数据并从匹配PipedInputStream文件中获得单独的线程副本。

于 2009-05-06T10:00:41.280 回答
0

You could make a queue based system, where you put the events on a queue/list and then have another thread which takes the events to be written, and write them out. This way the file writer will be asynchronous to the rest of the system, and your only delay will be adding an element to a list.

于 2009-05-06T08:30:40.653 回答