测试得出main线程配合一个线程使用时,耗时较低,当多个线程进行计算时,线程内计算及其耗时。
PS:条件有限,只在单台电脑上进行了测试。
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
// 倒计时锁存器
CountDownLatch latch = new CountDownLatch(1);
try {
long a1 = System.currentTimeMillis();
Future<Long> submit1 = threadPoolExecutor.submit(() -> {
Long reduce = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L, Long::sum);
latch.countDown();
long a2 = System.currentTimeMillis();
System.out.println("耗时(线程):"+(a2-a1));
return reduce;
});
// 主线程
long a3 = System.currentTimeMillis();
Long reduce1 = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L, Long::sum);
System.out.println(reduce1);
long a4 = System.currentTimeMillis();
System.out.println("耗时(主):"+(a4-a3));
// 线程等待
latch.await();
long sum = submit1.get()+reduce1;
System.out.println(sum+"耗时(总):"+(a4-a1));
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPoolExecutor.shutdown();
}
}
主线程+单个线程结果:
耗时(线程):418
耗时(主):326
1000000001000000000耗时(总):427
主线程+多个线程结果:
耗时(主):397
耗时(线程):1999
耗时(线程):2057
1000000001000000000耗时(总):2057