【发布时间】:2017-09-26 13:34:01
【问题描述】:
我正在尝试读取文件并将每一行添加到列表中。
Simple drawing explaining the goal
主类-
public class SimpleTreadPoolMain {
public static void main(String[] args) {
ReadFile reader = new ReadFile();
File file = new File("C:\\myFile.csv");
try {
reader.readFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
阅读器类 -
public class ReadFile {
ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
List<String> list = new ArrayList<>();
void readFile(File file) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != "") {
Runnable saver = new SaveToList(line,list);
executor.execute(saver);//calling execute method of ExecutorService
}
}
executor.shutdown();
while (!executor.isTerminated()) { }
}
}
保护类 -
public class SaveToList<E> implements Runnable{
List<E> myList;
E line;
public SaveToList(E line, List<E> list) {
this.line = line;
this.myList = list;
}
public void run() {
//modify the line
myList.add(line);
}
}
我尝试将许多保护程序线程添加到同一个列表中,而不是一个保护程序一个一个地添加到列表中。我想使用线程,因为我需要在添加到列表之前修改数据。所以我认为修改数据需要一些时间。所以并行这部分会减少时间消耗,对吧?
但这不起作用。我无法返回包含文件中所有值的全局列表。我只想从文件中获得一个全局值列表。所以代码肯定应该改变。如果有人可以指导我,将不胜感激。
即使在单个线程中逐一添加也可以,但使用线程池会更快,对吧?
【问题讨论】:
-
除了一个一个一个之外,您认为您可以如何添加到列表中?一件事必须进去;然后是下一个;然后是下一个。
-
你能详细说明什么不起作用吗? 但这不起作用。有点笼统
-
那你是说使用少线程不会影响插入部分的时间消耗?
-
他说的完全不是这个意思
-
请注意,
while ((line = br.readLine()) != "") {不会按照您的想法行事。见How do I compare strings in Java?
标签: java multithreading threadpool threadpoolexecutor