【问题标题】:How to write in file from multiple threads如何从多个线程写入文件
【发布时间】:2015-09-12 17:50:38
【问题描述】:

我有问题。我需要创建 9 个文件,每个文件都从线程名称调用。每个文件将被称为 1.txt、2.txt、3.txt 等。每个文件都将填充一个与文件名对应的符号(1.txt 文件为“1”)。每个文件应为 100 行,每行长度为 100 个字符。这项工作必须执行线程和 I\O。当使用多个线程时,我需要在生成的文件 super.txt 中读取这些文件的内容。

我的代码:

public class CustomThread extends Thread {

    Thread t;
    String threadName;

    CustomThread(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        if (t == null) {
            t = new Thread(this);
        }
        add(threadName);
    }

    public void add(String threadName) {
        File f = new File(threadName + ".txt");

        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("File does not exists!");
            }
        }

        FileWriter fw = null;
        try {
            fw = new FileWriter(f);
            for (int i = 0; i < 100; i++) {
                for (int j = 0; j < 100; j++) {
                    fw.write(threadName);
                }
                fw.write('\n');
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("File does not exists!");
        }
    }
}

我的主要:

public class Main {
    public static void main(String[] args) {

        CustomThread T1 = new CustomThread("1");
        T1.start();

        CustomThread T2 = new CustomThread("2");
        T2.start();

    }
}

第一个问题。我需要,使线程循环。看看我的主线:我创造了

CustomThread T1 = new CustomThread("1");
T1.start();

但是,我想循环创建 9 个文件。这该怎么做 ?

第二个问题。我需要从多个线程写入每个文件。

第三个问题。如何从结果文件中的多个线程写入thats文件的五个内容?

【问题讨论】:

    标签: java multithreading filereader filewriter


    【解决方案1】:

    我想循环创建 9 个文件。如何做到这一点?

    使用循环

    for (int i = 1; i <= 9; i++) {
       new CustomThread("" + i).start();
    }
    

    我需要从多个线程写入我的每个文件。

    你是怎么做到的?在启动线程之前打开文件并在使用它们时锁定它们。

    如何在结果文件中从多个线程写入该文件的五个内容?

    你能改一下这个问题吗?

    【讨论】:

    • 如何在结果文件中从多个线程写入?结果 super.txt 是包含所有这些文件的文件。
    • @Valeriu "在启动线程之前打开文件,并在使用它们时锁定它们。"你有什么疑问?
    • @彼得。我不明白你。如何做到这一点?
    • @Valeriu 我假设您知道如何打开文件并将其作为参数传递,我还假设您知道如何使用synchronized 并写入文件。我假设你编写了上面的代码,所以你已经知道如何完成大部分工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多