java循环次数多很慢的问题解决方法
解决方法:
直接上源码,本例子使用了分治编程,比普通for节省了一半的时间,可以复制运行一下,不用依赖第三方包。86400次循环内嵌套1000000次循环演示。
1.运行代码
public static void main(String[] args) throws InterruptedException, ExecutionException {
long begin=System.currentTimeMillis();
int sum=0;
for(int i=0;i<=86400;i++){
for(int j=0;j<=1000000;j++){
sum+=j;
}
}
System.out.println("结果值:"+sum);
System.out.println("消耗时间:"+(System.currentTimeMillis()-begin));
ForkJoinPool pool2=new ForkJoinPool();
long begin2=System.currentTimeMillis();
MyRecursiveTask myRecursiveTask = new MyRecursiveTask(0,86399);
ForkJoinPool pool=new ForkJoinPool();
pool.execute(myRecursiveTask);
System.out.println("结果值:"+myRecursiveTask.get());
pool.shutdown();
System.out.println("消耗时间:"+(System.currentTimeMillis()-begin2));
}
结果值:1200740640
消耗时间:65693
结果值:1200740640
消耗时间:32546
2.MyRecursiveTask.java
import java.util.concurrent.RecursiveTask;
public class MyRecursiveTask extends RecursiveTask<Integer>{
private int begin;
private int end;
public MyRecursiveTask(int begin, int end) {
super();
this.begin = begin;
this.end = end;
}
@Override
protected Integer compute() {
if((end-begin)!=0){
int min=(begin+end)/2;
MyRecursiveTask2 myRecursiveTaskLeft = new MyRecursiveTask2(begin,min);
MyRecursiveTask2 myRecursiveTaskRight = new MyRecursiveTask2(min+1,end);
this.invokeAll(myRecursiveTaskLeft,myRecursiveTaskRight);
int left=myRecursiveTaskLeft.join();
int right=myRecursiveTaskRight.join();
return left+right;
}else{
int sum=0;
for(int j=0;j<1000000;j++){
sum++;
}
return sum;
}
}
}
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1498