Java多线程消费一个list

在项目中,常常会需要处理一个list数据列表,使用多线程来加速数据的处理。

需要保证两点:

  1. 能灵活控制线程的数量
  2. 能够同步的完成一批list的数据

可以使用信号量和线程池,具体实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public static <T> void startWithMultiThread(List<T> list, int nThread, Consumer<T> func) {
if (CollectionUtils.isEmpty(list)) {
return;
}
if (nThread <= 0) {
return;
}
if (func == null) {
return;
}
if (CollectionUtils.isEmpty(list)) {
return;
}
Semaphore semaphore = new Semaphore(nThread);//定义几个许可
ExecutorService executorService = Executors.newFixedThreadPool(nThread);//创建一个固定的线程池
for (T obj : list) {
try {
semaphore.acquire();
executorService.execute(() -> {
try {
func.accept(obj);
semaphore.release();
} catch (Exception ex) {

}
});
} catch (InterruptedException e) {

}
}
executorService.shutdown();
}

作者

付威

发布于

2019-03-23

更新于

2020-08-10

许可协议

评论