特此添加具有 5 个线程的工作示例。只需将 test.txt 放在应用程序的 CLASS_PATH 中即可。
class MyRunnable implements Runnable {
List<List<String>> records;
MyRunnable(List<List<String>> records){
this.records = records;
}
public void run(){
for(List list : records){
System.out.println(Thread.currentThread().getName() + " : "+list.toString());
}
}}
主要课程 -
public class FileProcessThreads {
public List<List<String>> process(String fileName) throws IOException {
List<List<String>> records = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = br.readLine()) != null){
List<String> listValues = Arrays.asList(line.split(" "));
records.add(listValues);
}
System.out.println(records.size());
return records;
}
public static void main(String[] args) throws IOException {
FileProcessThreads fp = new FileProcessThreads();
List<List<String>> records = fp.process("test.txt");
ExecutorService es = Executors.newFixedThreadPool(5);
int recordsInEachThread = (int) (records.size()/5);
System.out.println(recordsInEachThread);
MyRunnable my1 = new MyRunnable(records.subList(0, recordsInEachThread));
MyRunnable my2 = new MyRunnable(records.subList(recordsInEachThread+1, recordsInEachThread*2));
MyRunnable my3 = new MyRunnable(records.subList(recordsInEachThread*2 + 1, recordsInEachThread*3));
MyRunnable my4 = new MyRunnable(records.subList(recordsInEachThread*3 + 1, recordsInEachThread*4));
MyRunnable my5 = new MyRunnable(records.subList(recordsInEachThread*4 + 1, records.size() - 1));
es.execute(my1);
es.execute(my2);
es.execute(my3);
es.execute(my4);
es.execute(my5);
es.shutdown();
}}