老师在课上说,当需要大量计算时,使用线程池会效率会更高,可我发现使用for循环计算累加值,耗时会少很多。这是为什么?
输出:
使用线程池耗时:6454
for耗时:84
public class LongAccumulatorDemo {
public static void main(String[] args) {
threadPool();
forLoop();
}
public static void threadPool() {
LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0);
ExecutorService service = Executors.newFixedThreadPool(8);
long s = System.currentTimeMillis();
IntStream.range(1, 10000000).forEach(i -> service.submit(() -> longAccumulator.accumulate(i)));
long e = System.currentTimeMillis();
service.shutdown();
while (!service.isTerminated()) {
}
System.out.println("使用线程池耗时:" + (e - s));
}
public static void forLoop() {
LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0);
long s = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
longAccumulator.accumulate(i);
}
long e = System.currentTimeMillis();
System.out.println("for耗时:" + (e - s));
}
}