我正在尝试学习Java 8并行流。我编写了以下代码,首先使用Executor,然后使用并行流。 似乎并行流需要两倍(10秒)的时间才能完成Executor方法所需的时间(5秒)。在我看来,并行流应该显示出类似的性能。有什么想法为什么并行流需要双倍的时间呢? 我的电脑有8个核心。
/**
*
*/
package com.shashank.java8.parallel_stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author pooja
*
*/
public class Sample {
public static int processUrl(String url) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Running Thread " + Thread.currentThread());
return url.length();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
usingExecutor();
usingParallelStream();
}
public static void usingParallelStream() {
Date start = new Date();
// TODO Auto-generated method stub
int total = buildUrlsList().parallelStream().mapToInt(Sample::processUrl).reduce(0, Integer::sum);
Date end = new Date();
System.out.println(total);
System.out.println((end.getTime() - start.getTime()) / 1000);
}
public static void usingExecutor() throws Exception {
Date start = new Date();
ExecutorService executorService = Executors.newFixedThreadPool(100);
List<Future> futures = new ArrayList<>();
for (String url : buildUrlsList()) {
futures.add(executorService.submit(() -> processUrl(url)));
}
// iterate through the future
int total = 0;
for (Future<Integer> future : futures) {
total += future.get();
}
System.out.println(total);
Date end = new Date();
System.out.println((end.getTime() - start.getTime()) / 1000);
}
public static List<String> buildUrlsList() {
return Arrays.asList("url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9");
}
}
Sample::processUrl
在做什么,所以无法真正帮助您。但很明显,在8核机器上使用100个线程的ExecutorService
根本不好。 - Eugene