我遇到了一个问题,我有多个线程写入同一个 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
最佳答案
为了使同步工作正常,您应该为所有线程使用相同的对象,例如:
...
synchronized (resultFile) {
...
关于java - 从多个线程可靠地写入一个 PrintWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774125/