1.创建线程池
package com.jinyatu.common.pool;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyThreadPool {
public static ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(
5,
Runtime.getRuntime().availableProcessors(),
10,
TimeUnit.SECONDS,
new LinkedBlockingDeque(30),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
}
2. 业务中使用线程池并发处理任务。
public void updateByBatch(List<VervelClient> clients) {
int tatol = clients.size();
//开启多线程处理
CountDownLatch countDownLatch = new CountDownLatch(tatol);
clients.forEach(vervelClient -> {
MyThreadPool.threadExecutor.execute(()->{
updateSelectiveById(vervelClient);
countDownLatch.countDown();
});
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}