gpt4 book ai didi

java - 使用多线程处理 'N' 项的列表

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

我有 N 项的 List,我想在固定数量的 线程之间按顺序划分此 List .

按顺序我的意思是,我想将1到N/4传递给第一个线程N/4 + 1到N/2到第二个线程,N/2+1 到 N 到第三个线程,现在,一旦所有线程完成其工作,我想通知主线程发送一些消息,表明所有处理已完成。

到目前为止我所做的是实现了ExecutorService

我做了这样的事情

ExecutorService threadPool = Executors.newFixedThreadPool(Number_of_threads); 
//List of items List
List <items>itemList = getList();
for (int i = 0 i < Number_of_threads ;i++ ) {
//how to divide list here sequentially and pass it to some processor while will process those items.
Runnable processor = new Processor(Start, End)
executor.execute(process);
}
if(executor.isTerminated()){
logger.info("All threads completed");
}
  • 如何将列表划分为连续的 block ?
  • 是否有更好的方法来实现此类功能?

最佳答案

如果您想要的是让所有线程尽快完成处理,并且项目数量不是很大,那么只需将每个项目一个 Runnable 发布到 newFixedThreadPool(NUMBER_OF_THREADS):

    ExecutorService exec = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
List<Future<?>> futures = new ArrayList<Future<?>>(NUMBER_OF_ITEMS);
for (Item item : getItems()) {
futures.add(exec.submit(new Processor(item)));
}
for (Future<?> f : futures) {
f.get(); // wait for a processor to complete
}
logger.info("all items processed");

如果您确实想要为每个线程提供列表的连续部分(但仍然希望它们尽快完成,并且还期望处理每个项目花费大约相同的时间),然后尽可能“均匀”地拆分项目,以便每个线程的最大项目数与最小数量相差不超过 1(例如:14 项目、4 线程,那么您希望分割为 [4,4,3,3],而不是例如 [3,3,3,5])。为此,您的代码将是例如

    ExecutorService exec = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
List<Item> items = getItems();
int minItemsPerThread = NUMBER_OF_ITEMS / NUMBER_OF_THREADS;
int maxItemsPerThread = minItemsPerThread + 1;
int threadsWithMaxItems = NUMBER_OF_ITEMS - NUMBER_OF_THREADS * minItemsPerThread;
int start = 0;
List<Future<?>> futures = new ArrayList<Future<?>>(NUMBER_OF_ITEMS);
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
int itemsCount = (i < threadsWithMaxItems ? maxItemsPerThread : minItemsPerThread);
int end = start + itemsCount;
Runnable r = new Processor(items.subList(start, end));
futures.add(exec.submit(r));
start = end;
}
for (Future<?> f : futures) {
f.get();
}
logger.info("all items processed");

关于java - 使用多线程处理 'N' 项的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30646474/

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