我有一個程序執行大量的計算並頻繁地將它們報告給一個文件。我知道頻繁的寫操作會讓程序慢下來,所以爲了避免這種情況,我希望有第二個線程專門用於寫操作。在Java中的並行線程中寫入文件的最佳方式是什麼?
現在,我這個班,我寫這樣做(性急可以跳過這個問題的結束):
public class ParallelWriter implements Runnable {
private File file;
private BlockingQueue<Item> q;
private int indentation;
public ParallelWriter(File f){
file = f;
q = new LinkedBlockingQueue<Item>();
indentation = 0;
}
public ParallelWriter append(CharSequence str){
try {
CharSeqItem item = new CharSeqItem();
item.content = str;
item.type = ItemType.CHARSEQ;
q.put(item);
return this;
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public ParallelWriter newLine(){
try {
Item item = new Item();
item.type = ItemType.NEWLINE;
q.put(item);
return this;
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public void setIndent(int indentation) {
try{
IndentCommand item = new IndentCommand();
item.type = ItemType.INDENT;
item.indent = indentation;
q.put(item);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public void end(){
try {
Item item = new Item();
item.type = ItemType.POISON;
q.put(item);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public void run() {
BufferedWriter out = null;
Item item = null;
try{
out = new BufferedWriter(new FileWriter(file));
while((item = q.take()).type != ItemType.POISON){
switch(item.type){
case NEWLINE:
out.newLine();
for(int i = 0; i < indentation; i++)
out.append(" ");
break;
case INDENT:
indentation = ((IndentCommand)item).indent;
break;
case CHARSEQ:
out.append(((CharSeqItem)item).content);
}
}
} catch (InterruptedException ex){
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
if(out != null) try {
out.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private enum ItemType {
CHARSEQ, NEWLINE, INDENT, POISON;
}
private static class Item {
ItemType type;
}
private static class CharSeqItem extends Item {
CharSequence content;
}
private static class IndentCommand extends Item {
int indent;
}
}
然後我做使用它:
ParallelWriter w = new ParallelWriter(myFile);
new Thread(w).start();
/// Lots of
w.append(" things ").newLine();
w.setIndent(2);
w.newLine().append(" more things ");
/// and finally
w.end();
雖然這工作得很好,但我想知道: 有沒有更好的方法來實現這個目標?
Similar questions:http://stackoverflow.com/questions/8602466/can-multi-threads-write-data-into-a-file-at-the-same-time – Vadzim 2015-06-11 12:57:28