计算10亿之内所有的数之和:
三等:
static void test() {
long starttime = System.currentTimeMillis();
long sum = 0;
for (Long i = 0L; i < 1000000000L; i++) {
sum += i;
}
long endtime = System.currentTimeMillis();
System.out.println(endtime - starttime);// test();//4807
}
六等:
public class ForkJoinTest extends RecursiveTask<Long> {
private long start;
private long end;
private long temp = 10000L;
private long sum;
public ForkJoinTest(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if ((end - start) < temp) {
for (Long i = start; i < end; i++) {
sum += i;
}
return sum;
} else {
Long middle = (end + start) / 2;
ForkJoinTest forkJoinTest = new ForkJoinTest(start, middle);
forkJoinTest.fork();
ForkJoinTest forkJoinTest2 = new ForkJoinTest(middle + 1, end);
forkJoinTest2.fork();
return forkJoinTest.join() + forkJoinTest2.join();
}
}
}
static void test2() throws ExecutionException, InterruptedException {
long starttime = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> forkJoinTest = new ForkJoinTest(0L, 1000000000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
Long aLong = submit.get();
long endtime = System.currentTimeMillis();
System.out.println(endtime - starttime);// test2();//4138
}
九等:
static void test3() {
long starttime = System.currentTimeMillis();
LongStream.rangeClosed(0L, 1000000000L).parallel().reduce(0, Long::sum);
long endtime = System.currentTimeMillis();
System.out.println(endtime - starttime);//test3()//271
}
本文通过三个不同等级的代码实现计算10亿以内所有数之和,分别是简单的for循环、使用Fork/Join框架和Java 8的Stream API并行处理。实验结果显示,Stream API的并行处理在效率上显著优于传统的循环和Fork/Join框架,分别用时271毫秒和4138毫秒,展示了并行计算的优势。
1万+

被折叠的 条评论
为什么被折叠?



