import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;
public class addTest {
public static void test1(){
long sum=0L;
long start=System.currentTimeMillis();
for(long i=1L;i<=10_0000_0000;i++){
sum+=i;
}
long end=System.currentTimeMillis();
System.out.println("sum:"+sum+",Time:"+(end-start));
}
public static void test2() throws ExecutionException, InterruptedException {
long sum=0L;
long start=System.currentTimeMillis();
ForkJoinPool forkJoinPool=new ForkJoinPool();
ForkJoinTask<Long> forkJoinTask=new ForkJoinDemo(0L,10_0000_0000L);
ForkJoinTask<Long> submit=forkJoinPool.submit(forkJoinTask);
sum=submit.get();
long end=System.currentTimeMillis();
System.out.println("sum:"+sum+",Time:"+(end-start));
}
public static void test3(){
long start=System.currentTimeMillis();
long sum=LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
long end=System.currentTimeMillis();
System.out.println("sum:"+sum+",Time:"+(end-start));
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
test1();
test2();
test3();
}
}
class ForkJoinDemo extends RecursiveTask<Long> {
private long start;
private long end;
private long temp=10000000L;
public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long sum=0L;
if((end-start)<temp){
for(long i=start;i<=end;i++){
sum+=i;
}
return sum;
}else{
long middle=(start+end)/2;
ForkJoinDemo task1=new ForkJoinDemo(start,middle);
task1.fork();
ForkJoinDemo task2=new ForkJoinDemo(middle+1,end);
task2.fork();
return task1.join()+task2.join();
}
}
}
ForkJoin特点:任务窃取,维护了一个双端队列,先执行完毕的线程抢未执行完的线程,会存在抢占问题。大数据量使用。
package com.example.goose.util;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
@Slf4j
public class TestJUC7 {
public static void main(String[] args) {
ForkJoinPool pool= new ForkJoinPool(4);
System.out.println(pool.invoke(new Te(5)));
}
}
class Te extends RecursiveTask<Integer>{
private int n=0;
public Te(int n){
this.n=n;
}
@Override
protected Integer compute() {
if(n==1){
return 1;
}
Te t1=new Te(n-1);
t1.fork();
int result=n+t1.join();
return result;
}
}