我遇到了一个问题,我有多个线程写入同一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
最佳答案
池停止后,您是否关闭PrintWriter
?
pool.shutdown();
final boolean terminated = pool.awaitTermination(8, TimeUnit.SECONDS);
if (!terminated) {
throw new IllegalStateException("pool shutdown timeout");
}
resultFile.close();