gpt4 book ai didi

java - 并行编程。计算()方法,java

转载 作者:太空宇宙 更新时间:2023-11-04 12:18:13 24 4
gpt4 key购买 nike

我有一个扩展RecursiveAction的类。同一个类包含以数组为参数的构造函数和compute()方法。在计算方法中,它接下来说:如果array长度大于500,则将该数组分成两半,并通过MergeSort.merge()方法对它们进行排序。如果数组长度小于 500,则只需对数组进行排序。

private static class SortTask extends RecursiveAction {
private final int THRESHOLD = 500;
private int[] list;
SortTask(int[] list) {
this.list = list;
}
@Override
protected void compute() {
if (list.length < THRESHOLD)
java.util.Arrays.sort(list);
else {
// Obtain the first half
int[] firstHalf = new int[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);


// Obtain the second half
int secondHalfLength = list.length - list.length / 2;
int[] secondHalf = new int[secondHalfLength];
System.arraycopy(list, list.length / 2,
secondHalf, 0, secondHalfLength);
// Recursively sort the two halves
invokeAll(new SortTask(firstHalf),
new SortTask(secondHalf));
// Merge firstHalf with secondHalf into list
MergeSort.merge(firstHalf, secondHalf, list);
}
}
}
}

它说“递归地对两半进行排序”,它是通过以下方式实现的:

invokeAll(new SortTask(firstHalf), new SortTask(secondHalf));

这是否意味着每次创建 new SortTask 对象时,都会调用 compute() 方法?

最佳答案

答案是否定的。Compute 不是 Task 构造函数的一部分。最简单的情况是池 shutdownNow() - 此调用将尝试终止/中断所有提交的任务。

每次新的SortTask创建ForkJoinPool时都会 fork 此任务:

public static void invokeAll(ForkJoinTask<?>... tasks) {
Throwable ex = null;
int last = tasks.length - 1;
for (int i = last; i >= 0; --i) {
ForkJoinTask<?> t = tasks[i];
if (t == null) {
if (ex == null)
ex = new NullPointerException();
}
else if (i != 0)
t.fork();
...
}

compute 方法是您的任务负载 - ForkJoinPool 将按其计划执行此操作。

来自ForkJoinTask javadoc :

The primary coordination mechanisms are fork(), that arranges asynchronous execution, and join(), that doesn't proceed until the task's result has been computed.

RecursiveTask 实现抽象方法:

protected final boolean exec() {
result = compute();
return true;
}

ForkJoinWorkerThread 有方法:

final void More execTask(ForkJoinTask<?> t) {
currentSteal = t;
for (;;) {
if (t != null)
t.doExec();
...
}

并且在doExec调用exec

final void doExec() {
if (status >= 0) {
boolean completed;
try {
completed = exec();
...
}

关于java - 并行编程。计算()方法,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com