JAVA多线程处理for循环
生活随笔
收集整理的這篇文章主要介紹了
JAVA多线程处理for循环
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public static void main(String[] args) {long start = System.currentTimeMillis();List<Integer> list = new ArrayList();for (int i = 0; i < 1000; i++) {list.add(i);}//定義線程數量為20,可根據服務器配置適當調整大小 Thread(list, 20);long end = System.currentTimeMillis();System.out.println("總時間 = " + (end - start));}
//此處有加鎖,不需要的同學可以自行改造
public synchronized static <T> void Thread(List<T> list, int nThread) {if (CollectionUtils.isEmpty(list) || nThread <= 0 || CollectionUtils.isEmpty(list)) {return;}Semaphore semaphore = new Semaphore(nThread);//定義幾個許可ExecutorService executorService = Executors.newFixedThreadPool(nThread);//創建一個固定的線程池for (T number : list) {try {semaphore.acquire();executorService.execute(() -> {//此處可以放入待處理的業務System.out.println("number:" + number);semaphore.release();});} catch (InterruptedException e) {}}executorService.shutdown();}
在數據量大的情況下對比直接循環效果很明顯。用上之后又可以加雞腿了~
總結
以上是生活随笔為你收集整理的JAVA多线程处理for循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年Q2邮件安全报告:钓鱼邮件季环
- 下一篇: android 课程表 拖拽,用自动排课