Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

new file: ForkJoinSample.java

  • Loading branch information...
commit dfb37f7915fecfa67b989d2a8443c86a006596e0 1 parent 7ea1ab0
Yasunaga1 authored
Showing with 51 additions and 0 deletions.
  1. +51 −0 Java7/ForkJoinSample.java
View
51 Java7/ForkJoinSample.java
@@ -0,0 +1,51 @@
+package Java7;
+
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.RecursiveTask;
+
+public class ForkJoinSample {
+
+ class Sum extends RecursiveTask<Long> {
+ private int start;
+ private int end;
+
+ public Sum(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ protected Long compute() {
+ long sum = 0;
+
+ if (end - start < 10) {
+ for (int i = start; i <= end; i++) {
+ sum += i;
+ }
+
+ return sum;
+ } else {
+ int middle = start + (end - start) / 2;
+ Sum sum1 = new Sum(start, middle);
+ Sum sum2 = new Sum(middle + 1, end);
+ sum1.fork();
+ sum+=sum2.compute();
+ sum+=sum1.join();
+
+ return sum;
+ }
+ }
+
+ }
+
+ public static void main(String[] args) {
+ ForkJoinSample forkJoinSample = new ForkJoinSample();
+ int start = 1;
+ int end = 22;
+ Sum sum = forkJoinSample.new Sum(start,end);
+
+ ForkJoinPool forkJoinPool = new ForkJoinPool();
+ long result = forkJoinPool.invoke(sum);
+ System.out.println(result);
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.