【发布时间】:2011-12-08 02:47:25
【问题描述】:
我遇到了一个问题,我有多个线程写入同一个 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
【问题讨论】:
-
你的池子够大吗?
-
我认为是。我将它设置为 10 个线程,并且没有耗尽内存。另外,我知道线程工作正常,因为我可以捕获 System.out 的输出并且它是准确的。
标签: java multithreading file-io io