我想了解java 8並行流。我寫了下面的代碼,首先使用Executor,然後使用並行流。 似乎並行流正在執行兩次(10秒)的時間與Executor方法(5秒)一樣多。在我看來,平行流也應該表現出類似的表現。任何想法爲什麼並行流需要兩倍時間? 我的電腦有8個內核。java 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");
}
}
將信息移入不同進程的時間可能是瓶頸。爲了獲得法國美食,你不會一路飛往法國。你花了很多時間來複制數據,沒有足夠的時間去做實際的工作。 –
好吧,它是關於*你如何*基準和*你基準。應該看看這裏:http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java。 – Eugene
除了我們不知道什麼'Sample :: processUrl'正在做什麼,所以不能真正幫助你。但很明顯,在一臺8核機器上有100個線程的「ExecutorServce」並不好。 – Eugene