【发布时间】:2013-11-11 13:28:05
【问题描述】:
这个问题似乎很常见,但是当多线程写入同一个文件(Excel)时,我遇到了问题。这是我的代码:
public class XLWriter {
private XLWriter() {
}
private static class SingletonHelper {
private static final XLWriter INSTANCE = new XLWriter();
}
public static synchronized XLWriter getInstance() {
return SingletonHelper.INSTANCE;
}
public static synchronized void writeOutput(Map<String, String> d) {
try {
--- Write file
} catch (Exception e) {
SOP("Not able to write output to the output file.");
}
}
public static void createWorkBook(String fileName, String sheetName)
throws IOException {
try {
-- Create workbook
} catch (WriteException e) {
System.out.println("Could not create workbook" + e);
}
}
我正在使用 testng 框架,10 个线程尝试写入同一个文件。许多线程无法写入它并进入异常块......有什么更好的方法来做到这一点?任何代码示例都会对我有很大帮助,因为我完成这个的时间非常少。谢谢。
【问题讨论】:
-
它是否适用于单线程?
createWorkBook方法不是synchronized。这是故意的吗?这两种方法哪一种失败了? -
你得到什么样的异常?
-
创建一个队列,每个线程将其数据写入其中。创建一个单独的写入器线程,它读取队列数据并保存到磁盘。
标签: java multithreading oop