ForkJoinTask
public class ForkJoinDemo extends RecursiveTask<Long> {
long tem = 20000;
long start = 0;
long end = 10_000_000;
<pre><code>public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if ((end - start) < tem) {
long sum = 0;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
long middle = (start + (end - start) / 2);
ForkJoinTask<Long> task1 = new ForkJoinDemo(start, middle);
ForkJoinTask<Long> task2 = new ForkJoinDemo(middle + 1, end);
task1.fork();
task2.fork();
return task1.join() + task2.join();
}
}
}
long start = 0;
long end = 10_000_000_00;
long sum = 0;
long startTime = System.currentTimeMillis();
for (long i = start; i <= end; i++) {
sum += i;
}
System.out.println(sum + ",time: " + (System.currentTimeMillis() - startTime));</p>
<p>startTime = System.currentTimeMillis();
ForkJoinDemo forkJoinDemo = new ForkJoinDemo(start,end);
forkJoinDemo.fork();
sum = forkJoinDemo.join();
System.out.println(sum + ",time: " + (System.currentTimeMillis() - startTime));
评论区