运行 Java 中值为 return 的动态线程数

Run a dynamic number of threads with value return in Java

所以基本上我正在尝试实施遗传算法,但让我担心的部分是优化。我正在尝试制作一个 Class 检查每个节点的适应性,但是我想 运行 同时检查,因为数据在检查过程中不会被更改,并且是相同的对于每个线程。我得出的结论是:

// check the gene for overlaps in room reservation
    for (int i=0;i<nrRooms;i++){
    FitnessThread thread = new FitnessThread(chromosome);
    }

使用线程的 运行 函数执行检查代码并用违规次数填充一个整数,以缩短它:

for(int j=0; j<individualLength; j++){
                if(chromosome.getGene((offset*individualLength)+j) * 
                    chromosome.getGene((offsetNext*individualLength)+j) != 0){
                    violations++;
                }
            }

我的问题是,如何在不以线性过程结束的情况下从每个单独的线程收集违规。我可以只声明一个线程数组然后同时启动它们,并在它们执行后分别从每个线程中收集吗?或者有其他方法吗?

提前致谢

您可以创建 Callable 并将它们提交到执行程序池,然后使用 Future.get(); 检索它们的结果。

ExecutorService executor = Executors.newFixedThreadPool(4); // or another kind of executor
List<Future<Foo>> futures = new ArrayList<>();
for(int i = 0;i < nrRooms; i++) {
    futures.add(executor.submit(new FitnessCallable(chromosome)));
}
...
// Time to check the results
for(Future<Foo> f : futures) {
    Foo result = f.get();  // Block and get the result
}

在Java8你可以做到

public class A {
    public static void main(String[] args) {
        List<Chromosome> chromosomes = new ArrayList<>();
        List<Pair<Double, Chromosome>> sortedByFitness 
                = chromosomes.parallelStream()
                .map(c -> Pair.of(c.finess(), c))
                .sorted(Comparator.comparing(p -> p.l).reversed())
                .limit(100) // best 100 values.
                .collect(Collectors.toList());
    }
}

class Pair<L, R>{
    L l;
    R r;

    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }

    public static <L, R> Pair<L, R> of(L l, R r) {
        return new Pair<>(l, r);
    }
}