Created
October 26, 2018 09:24
-
-
Save 0532/afdcd3e230a2bb8d33234845bfd01b57 to your computer and use it in GitHub Desktop.
forkjoin多线程执行任务
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 com.doraemoney.wk.quotecheckplatform.util; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.RecursiveAction; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* created by wanglichao@163.com on 2018/10/26. | |
*/ | |
public class PrintTask extends RecursiveAction{ | |
// 每个"小任务"最多只打印20个数 | |
private static final int MAX = 50; | |
private int start; | |
private int end; | |
PrintTask(int start, int end) { | |
this.start = start; | |
this.end = end; | |
} | |
@Override | |
protected void compute() { | |
// 当end-start的值小于MAX时候,开始打印 | |
if ((end - start) < MAX) { | |
for (int i = start; i < end; i++) { | |
System.out.println(Thread.currentThread().getName() + "的i值:" | |
+ i); | |
} | |
} else { | |
// 将大任务分解成两个小任务 | |
int middle = (start + end) / 2; | |
System.out.println("进入分解任务start:"+start+",middle:"+middle+",end:"+end); | |
PrintTask left = new PrintTask(start, middle); | |
PrintTask right = new PrintTask(middle, end); | |
// 并行执行两个小任务 | |
invokeAll(left,right); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
// 创建包含Runtime.getRuntime().availableProcessors()返回值作为个数的并行线程的ForkJoinPool | |
ForkJoinPool forkJoinPool = new ForkJoinPool();//todo使用线程池 | |
// 提交可分解的PrintTask任务 | |
forkJoinPool.submit(new PrintTask(0, 1000)); | |
forkJoinPool.awaitTermination(2, TimeUnit.SECONDS);//阻塞当前线程直到 ForkJoinPool 中所有的任务都执行结束 | |
// 关闭线程池 | |
forkJoinPool.shutdown(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment