【发布时间】:2021-02-15 23:13:28
【问题描述】:
我正在学习多线程,并希望使用不同的线程同时读取不同线程中的多个文本文件并在单个列表中获得结果。我有包含员工名字和姓氏的文本文件。
我写了下面的Employee类。
class Employee {
String first_name;
String last_name;
public Employee(String first_name, String last_name) {
super();
this.first_name = first_name;
this.last_name = last_name;
}
}
读取文件的类,用List来存储对象。
class FileReading {
List<Employee> employees = new ArrayList<Employee>();
public synchronized void readFile(String fileName) {
try {
FileReader fr = new FileReader(new File(fileName));
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
employees.add(new Employee(arr[0], arr[1]));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
带有主方法和线程的类。
public class TestMultithreading {
public static void main(String[] args) {
final FileReading fr = new FileReading();
Thread t1 = new Thread() {
public synchronized void run() {
fr.readFile("file1.txt");
}
};
Thread t2 = new Thread() {
public synchronized void run() {
fr.readFile("file2.txt");
}
};
Thread t3 = new Thread() {
public synchronized void run() {
fr.readFile("file3.txt");
}
};
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(fr.employees.size());
}
}
使用 join() 方法是否确保完成调用它的线程并继续执行另一个线程?如果是,多线程的意义何在? 有没有其他方法可以确保所有线程并行运行并在它们都在 main() 方法中完成后从它们那里收集结果?
【问题讨论】:
标签: java multithreading