Java多线程消费一个list

  • 2020 年 1 月 21 日
  • 筆記

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

需要保证两点:

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

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

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();      }