线程和文件写入 [英] Threads and file writing

查看:93
本文介绍了线程和文件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用20个线程的java程序。他们每个人都将结果写在一个名为 output.txt 的文件中。

I have a java program which uses 20 threads. Every one of them write their results in a file called output.txt.

我总是在 output.txt 中得到不同数量的行。

I always get a different number of lines in output.txt.

线程同步会出现问题吗?有没有办法处理这个?

Can it be a problem with the synchronization of threads? Is there a way to handle this?

推荐答案


这可能是线程同步的问题吗?

can it be a problem of synchronization of threads?

是。


有一种方法处理这个?

There's a way to handle this?

是的,确保通过同步相关的互斥锁来序列化写入。或者,只有一个线程实际输出到文件,并让所有其他线程简单地将队列文本写入一个写入线程从中抽取的队列。 (这样,20个主线程不会阻塞I / O.)

Yes, ensure that writes are serialized by synchronizing on a relevant mutex. Or alternately, have only one thread that actually outputs to the file, and have all of the other threads simply queue text to be written to a queue that the one writing thread draws from. (That way the 20 main threads don't block on I/O.)

重新使用互斥锁:例如,如果它们是所有使用相同的 FileWriter 实例(或其他),我将其称为 fw ,然后他们可以使用它作为互斥体:

Re the mutex: For instance, if they're all using the same FileWriter instance (or whatever), which I'll refer to as fw, then they could use it as a mutex:

synchronized (fw) {
    fw.write(...);
}

如果他们各自使用自己的 FileWriter 或者其他什么,找到他们共享的其他东西作为互斥锁。

If they're each using their own FileWriter or whatever, find something else they all share to be the mutex.

但是再一次,代表一个线程做I / O其他人可能也是一个不错的选择。

But again, having a thread doing the I/O on behalf of the others is probably also a good way to go.

这篇关于线程和文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆