Java实现并行功能
Java8 线程池异步处理 --> 针对小包大
MyTask 类中的 compute() 方法首先检查任务的规模是否小于等于 1。如果是,它直接返回任务的结果。否则,它将任务拆分成两个子任务(leftTask 和 rightTask),并使用 fork() 方法将它们提交到 ForkJoinPool 中执行。
import java.util.concurrent.ForkJoinPool;
public class ForkJoinExample {
public static void main(String[] args) {
// 创建一个 ForkJoinPool,线程数为可用处理器数量
ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
// 定义可并行任务
MyTask myTask = new MyTask(100);
// 提交任务到 ForkJoinPool 执行
forkJoinPool.submit(myTask);
// 等待任务完成
try {
myTask.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyTask extends RecursiveTask<Integer> {
private final int threshold;
public MyTask(int threshold) {
this.threshold = threshold;
}
@Override
protected Integer compute() {
if (threshold <= 1) {
return threshold;
} else {
int left = threshold / 2;
int right = threshold - left;
MyTask leftTask = new MyTask(left);
MyTask rightTask = new MyTask(right);
leftTask.fork();
rightTask.fork();
try {
return leftTask.join() + rightTask.join();
} catch (InterruptedException e) {
// 在这里处理异常
e.printStackTrace();
} catch (Throwable t) {
// 在这里处理异常
t.printStackTrace();
}
return 0;
}
}
}

浙公网安备 33010602011771号