我有一段代码
static class ReaderRunnable implements Runnable{
final BufferedReader br;
final Map<Integer, List<Integer>> edges;
ReaderRunnable(BufferedReader br, Map<Integer, List<Integer>> edges){
this.br = br;
this.edges = edges;
}
public void run() {
while (true) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
return;
}
if (line == null) {
return;
}
//some small code that adds the parsed line to a map
}
}
}
public class test {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(args[1]);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
ExecutorService pool = Executors.newFixedThreadPool(1);
}
}
如果我在main中调用new ReaderRunnable(br, edges).run()
,则程序运行时间仅为8秒。如果我拨打pool.submit(new ReaderRunnable(br, edges)).get()
,程序需要19秒才能运行。 Thread t = new Thread(new ReaderRunnable(br, edges)); t.start(); t.join();
也需要19秒
我知道将它放在一个单独的线程中是没有意义的,但是后来的目标是并行化代码 - 但是如果使用线程只有大约3倍的减速,为什么它这么慢?