将 BufferedWriter.write 推迟到另一个线程

发布于 2024-07-19 04:25:32 字数 144 浏览 6 评论 0原文

我有一个事件处理方案,它最终也应该写入文件; 当文件被刷新时,我无法延迟事件,即等待 BufferedWriter.write(String) 的末尾。

我正在寻找实现这一目标的最简单方法(是否有一个库可以做到这一点?我认为我不是唯一遇到此问题的人)

I have an event processing scheme which should also eventually write to file; I cannot afford to delay the event when the file is being flushed, i.e. waiting to the end of BufferedWriter.write(String).

I'm looking for the easiest way to achieve that (is there's a library doing that? I reckon that I'm not the only one who had this problem)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

划一舟意中人 2024-07-26 04:25:32

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

ExecutorService executor = Executors.newSingleThreadExecutor();

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

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

You could use an single threaded executor to perform the file writing for each event.

ExecutorService executor = Executors.newSingleThreadExecutor();

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

There would only be one thread and the executor would take care of queueing.

土豪 2024-07-26 04:25:32

基本上,您希望写入文件不会中断事件处理流程。

在这种情况下,您所需要做的就是将文件处理委托给单独的线程。

您的代码应该如下所示:

// 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

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
柏拉图鍀咏恒 2024-07-26 04:25:32

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

So long as you are keeping the same thread, you can use java.io.PipedOutputStream to store the data and have separate thread copy from the matching PipedInputStream to file.

末が日狂欢 2024-07-26 04:25:32

您可以创建一个基于队列的系统,将事件放在队列/列表中,然后使用另一个线程来写入事件并将其写出。 这样,文件编写器将与系统的其余部分异步,唯一的延迟是将元素添加到列表中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文