java并行出来文件_在Java中并行线程中写入文件的最佳方式是什么?

我有一个程序执行大量的计算,并经常报告给一个文件。我知道频繁的写入操作可能会使程序减慢很多,所以为了避免这种情况,我希望有一个专门用于写作操作的线程。

现在我正在用这个我写的班(不耐烦的可以跳到问题的结尾):

public class ParallelWriter implements Runnable {

private File file;

private BlockingQueue q;

private int indentation;

public ParallelWriter( File f ){

file = f;

q = new LinkedBlockingQueue();

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();

虽然这样做很好,我想知道:

有没有更好的方式来完成这个?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值