Java多執行緒消費一個list
- 2020 年 1 月 21 日
- 筆記
在項目中,常常會需要處理一個list數據列表,使用多執行緒來加速數據的處理。
需要保證兩點:
- 能靈活控制執行緒的數量
- 能夠同步的完成一批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(); }

