Java代码基于线程池多线程并发读取不同文件内容的案例
时间: 2023-07-11 18:36:33 浏览: 109
好的,以下是一个基于线程池多线程并发读取不同文件内容的Java代码案例:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FileReadThreadPool {
private static final int THREAD_POOL_SIZE = 5; // 线程池大小
private ExecutorService executorService; // 线程池
private File[] files; // 需要读取的文件数组
public FileReadThreadPool(File[] files) {
this.files = files;
this.executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public void readFiles() {
for (File file : files) {
executorService.execute(new FileReaderRunnable(file));
}
executorService.shutdown();
}
private static class FileReaderRunnable implements Runnable {
private File file;
FileReaderRunnable(File file) {
this.file = file;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(Thread.currentThread().getName() + " : " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
使用方法如下:
```java
public static void main(String[] args) {
File[] files = {new File("file1.txt"), new File("file2.txt"), new File("file3.txt")};
FileReadThreadPool fileReadThreadPool = new FileReadThreadPool(files);
fileReadThreadPool.readFiles();
}
```
在这个例子中,我们使用了一个固定大小的线程池(`newFixedThreadPool`),并将每个文件的读取任务放入线程池中执行。每个读取任务都是一个实现了`Runnable`接口的内部类`FileReaderRunnable`,它负责打开文件、读取文件内容并输出到控制台。
阅读全文