嗨,我是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/

10-10 22:38