我有List
个N
项,我希望将这个List
按顺序划分为固定数量的threads
。
顺序我的意思是,我想将1 to N/4
传递给第一个thread
,将N/4 + 1 to N/2
传递给第二个帖子,将N/2+1 to N
传递给第三个thread
, threads
已完成工作,我想通知主thread
发送一条消息,说明所有处理都已完成。
到目前为止我所做的是我实施了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");
}
答案 0 :(得分:14)
如果您想要的是让所有线程尽快完成处理并且项目数量不是巨大那么只需将每个项目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");
如果确实希望为每个帖子提供列表的连续部分(但仍希望它们尽快完成,并且还希望处理每个项目花费的时间大致相同),然后尽可能“均匀”地分割项目,以便每个线程的最大项目数与最小数量不同,不超过一个(例如: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");