public static void main(String[] args) {
long start = System.currentTimeMillis();
List 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 void Thread(List 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();
}
在数据量大的情况下对比直接循环效果很明显。用上之后又可以加鸡腿了~