简体   繁体   中英

How to write in file from multiple threads

I have problem. I need to create 9 files, each called from thread name. Each file will be called 1.txt, 2.txt, 3.txt etc. Each file will be filled with a symbol that corresponds to the name of the file (1.txt file is "1"). Each file should be 100 lines, each line length is 100 characters. This work must perform threads of execution and I\\O. I need to read the contents of these files in the resulting file super.txt, when using several threads.

My code:

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!");
        }
    }
}

My main:

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

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

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

    }
}

First question. I need, to make threads in cycle. Look on my main: I create

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

But, i want to create 9 files in cycle. How to do this ?

Second question. I need to write in every my file from multiple threads.

Third question. How to write from multiple threads in result file five contents of thats files ?

i want to create 9 files in cycle. How to do this ?

Use a loop

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

I need to write in every my file from multiple threads.

How do you do this? Open the files before you start the threads and lock them when ever you use them.

How to write from multiple threads in result file five contents of thats files ?

Can you rephrase that question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM