从多个线程可靠地写入一个 PrintWriter
我遇到了一个问题,我有多个线程写入同一个 PrintWriter,但并非所有数据都写入文件。我知道多线程部分工作正常,因为我可以将所有内容打印到控制台。同步写入语句似乎不起作用。可能是什么问题?
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
for (Integer i : map.keySet()) {
final Collection<String[]> set = map.get(i);
pool.submit(new Runnable() {
public void run() {
StringBuffer sb = Matcher.performCollectionMatch(params);
synchronized (this) {
resultFile.print(sb); //this is a PrintWriter - it does NOT capture all sb
resultFile.flush();
System.out.print(sb); //this actually prints out ALL sb
}
}
});
} //FOR loop
I'm running into an issue where I have multiple threads that write to the same PrintWriter and not all the data is getting written to the file. I know the multi-threaded part is working correctly since I can print everything to the console. Synchronizing the write statements does not seem to be working. What could be the problem?
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
for (Integer i : map.keySet()) {
final Collection<String[]> set = map.get(i);
pool.submit(new Runnable() {
public void run() {
StringBuffer sb = Matcher.performCollectionMatch(params);
synchronized (this) {
resultFile.print(sb); //this is a PrintWriter - it does NOT capture all sb
resultFile.flush();
System.out.print(sb); //this actually prints out ALL sb
}
}
});
} //FOR loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了使同步工作正常,您应该为所有线程使用相同的对象,例如:
For synchronization to work, you should use the same object for all threads, e.g.:
池停止后是否关闭
PrintWriter
?Do you close the
PrintWriter
after the pool stops?一种更简单的解决方案是确保池中只有一个线程。这样您就不需要同步写入,因为只有一个线程。
瓶颈很可能是磁盘访问,因此添加更多线程可能没有帮助。
A simpler solution is to ensure there is only one thread in the pool. This way you don't need to synchonize writing as there is only one thread.
It is quite likely the bottle neck is you disk access so adding more threads may not help.