【发布时间】: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