发表更新 付威 1 分钟读完 (大约162个字)0次访问
Java多线程消费一个list
在项目中,常常会需要处理一个list数据列表,使用多线程来加速数据的处理。
需要保证两点:
- 能灵活控制线程的数量
- 能够同步的完成一批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(); }
|
You need to set install_url
to use ShareThis. Please set it in _config.yml
.