多线程的题目
关于#java#的问题,请各位专家解答!(开发工具-eclipse)
package com.dt.zt.admin;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// randomName("G:\\com_qfedu\\name.txt");
Fwriter fwriter = new Fwriter("G:\\com_qfedu\\name.txt");
Fread fread = new Fread("G:\\com_qfedu\\name.txt", fwriter);
fread.start();
fwriter.start();
}
public static void randomName(String fileName){
//创建字符串数组保存名字
String[] names = new String[10];
//创建文件对象
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
for (int i = 0; i < 10; i++) {
//按行读取数据
names[i] = bufferedReader.readLine();
}
Random random = new Random();
for (int i = 0; i < 3; i++) {
//随机打印名字
System.out.println(names[random.nextInt(10)]);
//休眠3秒
Thread.sleep(3000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Fread extends Thread {
private String fileName;
private Thread t;
public StringBuilder stringBuilder = new StringBuilder();
public Fread(String fileName, Thread t) {
this.fileName = fileName;
this.t = t;
}
@Override
public void run() {
try {
t.join();
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
String str = null;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
System.out.println("stringBuilder = " + stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Fwriter extends Thread{
private String fileName;
public Fwriter(String fileName){
this.fileName = fileName;
}
@Override
public void run() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName, true));
for (int i = 0; i < 10; i++) {
bufferedWriter.write("\r\n" + i + Thread.currentThread().getName());
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}