【发布时间】:2019-01-22 23:32:07
【问题描述】:
我正在尝试提高在单线程中运行的项目中当前代码的性能。代码正在做这样的事情: 1. 获取 10000000 个对象的第一个列表。 2. 获取 10000000 个对象的第二个列表。 3. 将这两个(经过一些更改)合并到第三个列表中。
Instant s = Instant.now();
List<Integer> l1 = getFirstList();
List<Integer> l2 = getSecondList();
List<Integer> l3 = new ArrayList<>();
l3.addAll(l1);
l3.addAll(l2);
Instant e = Instant.now();
System.out.println("Execution time: " + Duration.between(s, e).toMillis());
这里是获取和组合列表的示例方法
private static List<Integer> getFirstList() {
System.out.println("First list is being created by: "+ Thread.currentThread().getName());
List<Integer> l = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
l.add(i);
}
return l;
}
private static List<Integer> getSecondList() {
System.out.println("Second list is being created by: "+ Thread.currentThread().getName());
List<Integer> l = new ArrayList<>();
for (int i = 10000000; i < 20000000; i++) {
l.add(i);
}
return l;
}
private static List<Integer> combine(List<Integer> l1, List<Integer> l2) {
System.out.println("Third list is being created by: "+ Thread.currentThread().getName());
ArrayList<Integer> l3 = new ArrayList<>();
l3.addAll(l1);
l3.addAll(l2);
return l3;
}
我正在尝试将上面的代码重写如下:
ExecutorService executor = Executors.newFixedThreadPool(10);
Instant start = Instant.now();
CompletableFuture<List<Integer>> cf1 = CompletableFuture.supplyAsync(() -> getFirstList(), executor);
CompletableFuture<List<Integer>> cf2 = CompletableFuture.supplyAsync(() -> getSecondList(), executor);
CompletableFuture<Void> cf3 = cf1.thenAcceptBothAsync(cf2, (l1, l2) -> combine(l1, l2), executor);
try {
cf3.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Instant end = Instant.now();
System.out.println("Execution time: " + Duration.between(start, end).toMillis());
executor.shutdown();
单线程代码的执行时间为 4-5 秒,而多线程代码的执行时间为 6 秒以上。我做错了吗?
【问题讨论】:
标签: asynchronous java-8 completable-future