for循环中的多个线程

问题描述 投票:-1回答:1

我有一个方法需要为列表中的每个元素调用,然后将此列表返回给另一个类中的调用者。我想为每个元素创建一个Thread,但我很难理解如何做到这一点。

public List<MyList> threaded(List<Another> another) {
    List<MyList> myList= new ArrayList<>();
    Visibility visi = new Visibility();

    Thread[] threads = new Thread[another.size()];
    for (int i = 0; i < another.size(); i++) {
        visi = test(another.get(i));
        myList.add(visi);
    }
    return myList;
}

所以我已经定义了一个与another列表中的元素数匹配的线程数组。要在循环中使用每个线程,然后在执行完所有线程后返回myList就是我丢失的地方。

java multithreading java-threads
1个回答
4
投票

这看起来像Stream.parallelStream()的完美用例

public List<MyList> threaded(List<Another> another) {
    return another.parallelStream()
                  .map(a -> test(a));
                  .collect(Collectors.toList());
}

这将在每个test上调用Another并使用尽可能多的cpus将结果收集为List(最多为您拥有的对象数)

是的,您可以为每个创建一个Thread,除了这样做效率更低,更复杂。

© www.soinside.com 2019 - 2024. All rights reserved.