JAVA多线程处理for循环
生活随笔
收集整理的這篇文章主要介紹了
JAVA多线程处理for循环
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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);}//定義線程數(shù)量為20,可根據(jù)服務(wù)器配置適當(dāng)調(diào)整大小 Thread(list, 20);long end = System.currentTimeMillis();System.out.println("總時(shí)間 = " + (end - start));}
//此處有加鎖,不需要的同學(xué)可以自行改造
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);//定義幾個(gè)許可ExecutorService executorService = Executors.newFixedThreadPool(nThread);//創(chuàng)建一個(gè)固定的線程池for (T number : list) {try {semaphore.acquire();executorService.execute(() -> {//此處可以放入待處理的業(yè)務(wù)System.out.println("number:" + number);semaphore.release();});} catch (InterruptedException e) {}}executorService.shutdown();}
在數(shù)據(jù)量大的情況下對(duì)比直接循環(huán)效果很明顯。用上之后又可以加雞腿了~
總結(jié)
以上是生活随笔為你收集整理的JAVA多线程处理for循环的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年Q2邮件安全报告:钓鱼邮件季环
- 下一篇: android 课程表 拖拽,用自动排课