我遇到了一个问题,其中有多个线程写入同一个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
你的泳池尺寸够大吗? –
我认为是。我将它设置为10个线程,并且没有耗尽内存。另外,我知道这些线程正在正确地完成工作,因为我可以捕获System.out的输出并且它是准确的。 – banncee