Last active
December 19, 2015 02:08
-
-
Save nazarov-yuriy/5880702 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Date; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ForkJoinPool; | |
import algorithm.Solver; | |
/** | |
* @author nazarov | |
*/ | |
public class ExecutorTest { | |
public static void main(String[] args) throws ExecutionException, InterruptedException { | |
final ForkJoinPool pool = new ForkJoinPool(4); | |
final Solver solver = new Solver(0, 200000000); | |
double start = new Date().getTime()/1000.0; | |
pool.invoke(solver); | |
double end = new Date().getTime()/1000.0; | |
System.out.println(solver.result); | |
System.out.print("Done in: "); | |
System.out.print(end-start); | |
System.out.println(" s"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.927317886402193 | |
Done in: 27.70899987220764 s |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package algorithm; | |
import java.util.concurrent.RecursiveAction; | |
/** | |
* @author nazarov | |
*/ | |
public class Solver extends RecursiveAction { | |
private int _from; | |
private int _to; | |
public double result; | |
public Solver(int from, int to) { | |
_from = from; | |
_to = to; | |
} | |
@Override | |
protected void compute() { | |
if (_to - _from < 1000000) { | |
result = 0; | |
for(int i = _from; i < _to; i++) | |
result += Math.sin(i); | |
} else { | |
int mid = _from + (_to-_from) / 2; | |
Solver s1 = new Solver(_from, mid); | |
s1.fork(); | |
Solver s2 = new Solver(mid, _to); | |
s2.compute(); | |
s1.join(); | |
result = s1.result + s2.result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment