发烧友 21:58:01
import java.util.Date;
import java.util.concurrent.RecursiveTask;
public class TstForkJoin {
public static void main(String args[]) {
new TstForkJoin().start();
}
private void start() {
/*ForkJoinPool forkJoinPool = new ForkJoinPool();
Future<Integer> result = forkJoinPool.submit(new Calculator(0, 10000));
try {
System.out.print(result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}*/
System.out.println(new Date());
TstFJ1 tstFJ1 = new TstFJ1(4000);
TstFJ2 tstFJ2 = new TstFJ2(7000);
tstFJ1.fork();
tstFJ2.fork();
System.out.println(new Date());
Integer sum = tstFJ1.join() + tstFJ2.join();
System.out.println(new Date());
System.out.print(sum);
}
static class Calculator extends RecursiveTask<Integer> {
private static final int THRESHOLD = 100;
private int start;
private int end;
public Calculator(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum = 0;
if ((start - end) < THRESHOLD) {
for (int i = start; i < end; i++) {
sum += i;
}
} else {
int middle = (start + end) / 2;
Calculator left = new Calculator(start, middle);
Calculator right = new Calculator(middle + 1, end);
left.fork();
right.fork();
sum = left.join() + right.join();
}
return sum;
}
}
class TstFJ1 extends RecursiveTask<Integer> {
Integer times;
public TstFJ1(Integer times) {
System.out.println(times);
this.times = times;
}
@Override
protected Integer compute() {
try {
Thread.sleep(times);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times > 5000) {
return 1;
} else {
return 0;
}
}
}
class TstFJ2 extends RecursiveTask<Integer> {
Integer times;
public TstFJ2(Integer times) {
System.out.println(times);
this.times = times;
}
@Override
protected Integer compute() {
try {
Thread.sleep(times);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times > 5000) {
return 1;
} else {
return 0;
}
}
}
}
韩宏远 11:37:10
http://www.iteye.com/topic/643724
http://www.infoq.com/cn/articles/fork-join-introduction/
韩宏远 11:39:35
发烧友 21:58:57
写了一个并行计算的例子,可以用在接口校验上
发烧友 22:00:29
Wed Jun 29 21:56:39 CST 2016
4000
7000
Wed Jun 29 21:56:39 CST 2016
Wed Jun 29 21:56:46 CST 2016
1
发烧友 22:05:04
两个任务可以看做校验任务,校验正确返回0,错误返回1,一个4秒一个7秒,并行运算结果用时7秒
如果两个都返回0,认为校验正确,则执行文档插入,否则返回错误,
明天傲冰把校验改为并行方式