gpt4 book ai didi

java - ForkJoinPool 结果从未到达

转载 作者:行者123 更新时间:2023-12-02 09:02:49 24 4
gpt4 key购买 nike

嗨,我是 Java 并发的新手,我正在尝试通过 fork join 并将任务分成多个部分来使列表内容加倍。任务已完成,但结果从未到达。

package com.learning;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

class DoubleNumbers extends RecursiveTask<List<Integer>> {
private final List<Integer> listToDo;
public DoubleNumbers(List<Integer> list) {
System.out.println("Cons Called"+list.get(0));
this.listToDo = list;
}

@Override
protected List<Integer> compute() {
List<DoubleNumbers> doubleNumbersList= new ArrayList<>();
System.out.println(Thread.currentThread().toString());
for (int i = 0; i < listToDo.size(); i++) {
listToDo.set(i, listToDo.get(i) * 2);
}
return listToDo;
}
}

public class FJPExample {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 149; i++) {
arrayList.add(i, i);
}
ForkJoinPool forkJoinPool = new ForkJoinPool(4);

System.out.println(forkJoinPool.getParallelism());
DoubleNumbers doubleNumbers = new DoubleNumbers(arrayList.subList(0, 49));
DoubleNumbers doubleNumbers50ToNext = new DoubleNumbers(arrayList.subList(50, 99));
DoubleNumbers doubleNumbers100ToNext = new DoubleNumbers(arrayList.subList(100, 149));
forkJoinPool.submit(doubleNumbers);
forkJoinPool.execute(doubleNumbers50ToNext);
forkJoinPool.execute(doubleNumbers100ToNext);
do {
System.out.println("Parallel " + forkJoinPool.getParallelism());
System.out.println("isWorking" + forkJoinPool.getRunningThreadCount());
System.out.println("isQSubmission" + forkJoinPool.getQueuedSubmissionCount());
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
//
}
} while ((!doubleNumbers.isDone()) || (!doubleNumbers50ToNext.isDone()) || (!doubleNumbers100ToNext.isDone()));
forkJoinPool.shutdown(); // Line 56

arrayList.addAll(doubleNumbers.join());
arrayList.addAll(doubleNumbers50ToNext.join());
arrayList.addAll(doubleNumbers100ToNext.join());
System.out.println(arrayList.size());
arrayList.forEach(System.out::println);
}
}

如果我调试我的任务,我会发现数字加倍,但结果从未到达第 56 行

最佳答案

问题出在代码 arrayList.addAll(doubleNumbers.join()) ,第 54、55 和 56 行,因为这可能会导致 ConcurrentModificationException。所以,你可以做的是,用下面的行替换这些行,它就会起作用(它会起作用,因为你在第 #36 行使用了 arrayList.subList,它由相同的 arraylist 支持,请阅读其 javadoc 以获取更多信息)

doubleNumbers.join();
doubleNumbers50ToNext.join();
doubleNumbers100ToNext.join();

关于java - ForkJoinPool 结果从未到达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60035833/

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