## **关于线程池的调用(自定义线程池)**
ThreadPoolExecutor threadPoolExecutor = ThreadUtil.newExecutor(3, 1000);
初始线程数为corePoolSize 指定的大小 : 3
最大线程数限制 指定的大小 : 1000
默认使用LinkedBlockingQueue,默认队列大小为1024(最大等待数1024)
当运行线程大于corePoolSize放入队列,队列满后抛出异常
推荐 以后 使用 ExecutorBuilder
ThreadPoolExecutor threadPoolExecutor1 = ExecutorBuilder.create()
//初始线程数 2
.setCorePoolSize(2)
// 最大线程数 20
.setMaxPoolSize(20)
//指定线程等待队列长度 默认1024超过抛出异常
.setWorkQueue(new LinkedBlockingQueue<>(100)).build();
/****************************************/
**测速代码如下**
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
numList.add(i);
}
AtomicInteger atomicInteger = new AtomicInteger();
ThreadPoolExecutor threadPoolExecutor1 = ExecutorBuilder.create()
.setCorePoolSize(2)
.setMaxPoolSize(20)
.setWorkQueue(new LinkedBlockingQueue<>(numList.size())).build();
for (int i = 0; i < numList.size(); i++) {
int finalI = i;
threadPoolExecutor1.submit(() -> {
atomicInteger.getAndIncrement();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
show(numList.get(finalI));
System.out.println("atomicInteger 统计"+Thread.currentThread().getName() +
"当前执行进度 " + atomicInteger + "/" + numList.size());
});
}
//如果需要返回值或者返回请求啥的 就添加下面得代码;
threadPoolExecutor.shutdown();
try {
//当线程池中的线程阻塞1分钟后进入shutdownNow()方法中关闭线程
if (!threadPoolExecutor.awaitTermination(5, TimeUnit.MINUTES)) {
threadPoolExecutor.shutdownNow();
}
} catch (InterruptedException e) {
threadPoolExecutor.shutdownNow();
}
System.out.println("完成");
}
public static void show(Integer num){
System.out.println("第"+num+"只猫");
}
关于线程池的调用 之 自定义线程池
最新推荐文章于 2024-06-02 17:50:48 发布