<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.CharsetUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
File file = new File("test.txt");
int coreThreads = Runtime.getRuntime().availableProcessors();
ExecutorService executor = new ThreadPoolExecutor(
coreThreads,
coreThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1000),
ThreadUtil.newNamedThreadFactory("file-processor-", false),
new ThreadPoolExecutor.CallerRunsPolicy()
);
try (BufferedReader reader = FileUtil.getReader(file, CharsetUtil.CHARSET_UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
final String currentLine = line;
executor.execute(() -> processLine(currentLine));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
System.err.println("线程池未能在指定时间内终止");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void processLine(String line) {
System.out.println(Thread.currentThread().getName() + " 处理: " + line);
}
}