从多个线程写入文本文件? [英] Write to text file from multiple threads?

查看:101
本文介绍了从多个线程写入文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有20个线程用println()函数写入一个名为results.txt的文件。我如何同步它们?

i have 20 threads that write with the println() function on a file called results.txt. How can i synchronize them all?

我注意到每次我的程序运行时,我在results.txt中都有不同数量的文本行。

I note every time my program run i have different number of lines of text in results.txt.

谢谢。

推荐答案

通过包含 synchronized方法写入文件。一次只能有一个线程执行该方法。

Access the file through a class that contains a synchronized method to write to the file. Only one thread at a time will be able to execute the method.

我认为Singleton模式适合您的问题:

I think that Singleton pattern would fit for your problem:

package com.test.singleton;

public class Singleton {
    private static final Singleton inst= new Singleton();

    private Singleton() {
        super();
    }

    public synchronized void writeToFile(String str) {
        // Do whatever
    }

    public Singleton getInstance() {
        return inst;
    }

}

每次需要写入你的文件,你只需要打电话:

Every time you need to write to your file, you only would have to call:

Singleton.getInstance().writeToFile("Hello!!");

这篇关于从多个线程写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆