• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

把复杂任务拆分成多个子任务,最终把子任务结果再做一个合并

siyviznar0y5070.png

包juc。分叉连接;

导入Java。util。并发。执行异常;

导入Java。util。并发。forkjoinpool

导入Java。util。并发。forkjointask

导入Java。util。并发。recursivetask

我的任务类扩展了RecursiveTaskInteger {

//拆分的时候,差值不能超过10

私有静态最终整数值=10;

私有int begin//拆分开始值

私有int end//拆分结束值

私有int结果;//返回结果

//创建有参构造

public MyTask(int begin,int end){

this.begin=开始

this.end=end

}

//拆分和合并过程

@覆盖

受保护的整数计算(){

//判断相加的两个数的差值是否大于10

if((end - begin)=VALUE) {

//相加操作

for(int I=begin;我=结束;i ) {

结果=结果我;

}

} else {//进一步拆分

//获取中间值

int middle=(begin end)/2;

//拆分左边

MyTask task01=new MyTask(begin,middle);

//拆分右边

我的任务task02=新的我的任务(中间1,结束);

任务01。fork();

任务02。fork();

//合并结果

结果=任务01。join()任务02。join();

}

返回结果;

}

}

公共类FrokJoinDemo {

公共静态void main(String[] args)引发ExecutionException、InterruptedException {

//创建我的任务对象

MyTask myTask=new MyTask(0,100);

//创建分支合并池对象

ForkJoinPool ForkJoinPool=new ForkJoinPool();

forkJoinTask整数forkJoinTask=forkjoinpool。提交(我的任务);

//获取最终合并之后结果

整数result=forkjointask。get();

System.out.println(结果);

//关闭池对象

forkjoinpool。关闭();

}

}

Link to comment
Share on other sites