并发执行任务
程序员文章站
2022-07-23 08:41:10
并发执行任务 ......
并发执行任务
1 import java.util.concurrent.executionexception; 2 import java.util.concurrent.forkjoinpool; 3 import java.util.concurrent.forkjointask; 4 import java.util.concurrent.recursivetask; 5 6 /** 7 * 并发执行任务 8 */ 9 public class counttask extends recursivetask<integer> { 10 11 private static final long serialversionuid = 1l; 12 private static final int threshold = 2; //阈值 13 private int start; 14 private int end; 15 16 public counttask(int start,int end) { 17 this.start = start; 18 this.end = end; 19 } 20 21 @override 22 protected integer compute() { 23 int sum = 0; 24 //如果任务足够小就计算任务 25 boolean cancompute = (end - start) <= threshold; 26 if(cancompute) { 27 for (int i = start; i <= end; i++) { 28 sum += i; 29 } 30 }else { 31 //如果任务大于阈值 就分裂成两个子任务计算 32 int middle = (start + end) / 2; 33 counttask lefttask = new counttask(start, middle); 34 counttask righttask = new counttask(middle + 1, end); 35 lefttask.fork(); 36 righttask.fork(); 37 //等待子任务执行完成 并得到其结果 38 int leftresult = lefttask.join(); 39 int rightresult = righttask.join(); 40 //合并子任务 41 sum = leftresult + rightresult; 42 } 43 return sum; 44 } 45 46 public static void main(string[] args) { 47 forkjoinpool forkjoinpool = new forkjoinpool(); 48 //生成一个计算任务,负责计算1+2+3+4 49 counttask task = new counttask(1,4); 50 //执行一个任务 51 forkjointask<integer> result = forkjoinpool.submit(task); 52 try { 53 system.out.println(result.get()); 54 } catch (interruptedexception e) { 55 e.printstacktrace(); 56 } catch (executionexception e) { 57 e.printstacktrace(); 58 } 59 } 60 }