Java8新特性之并行流与串行流
前言:
Java8新特性之并行流与串行流
1、ForkJoinCalculateTest
package com.chenheng;
import com.chenheng.java8.ForkJoinCalculate;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;
/**
* @author chenheng
* @date 2021/11/14 21:19
*/
@SpringBootTest
public class ForkJoinCalculateTest {
@Test
void test01(){
Instant start = Instant.now();
ForkJoinPool pool = new ForkJoinPool();
ForkJoinCalculate task = new ForkJoinCalculate(0, 10000000000L);
Long sum = pool.invoke(task);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
}
@Test
void test02(){
Instant start = Instant.now();
long sum = 0;
for (long i = 0; i < 10000000000L; i++) {
sum += i;
}
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
}
@Test
void test03(){
Instant start = Instant.now();
long sum = LongStream.rangeClosed(0, 10000000000L)
.parallel()
.reduce(0, Long::sum);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
}
}
2、ForkJoinCalculate类
package com.chenheng.java8;
import java.util.concurrent.RecursiveTask;
/**
* @author chenheng
* @date 2021/11/14 21:07
*/
public class ForkJoinCalculate extends RecursiveTask<Long> {
private static final long serialVersionUID = 12432143423L;
private long start;
private long end;
private static final long THRESHOLD = 10000;
public ForkJoinCalculate(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long length = end - start;
if (length <= THRESHOLD) {
long sum = 0;
for (long i = start; i < end; i++) {
sum += i;
}
return sum;
} else {
long middle = (start + end) / 2;
ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
//拆分子任务,同时压入线程队列
left.fork();
ForkJoinCalculate right = new ForkJoinCalculate(middle + 1, end);
right.fork();
return left.join() + right.join();
}
}
}