public Map<String,Object> typeNum() throws InterruptedException {
Map<String,Object> result = new HashMap<>();
/**手写线程池
* @param corePoolSize 核心池大小 int
* @param maximumPoolSize 最大池大小 int
* @param keepAliveTime 保活时间 long(任务完成后要销毁的延时)
* @param unit 时间单位 决定参数3的单位,枚举类型的时间单位
* @param workQueue 工作队列 用于存储任务的工作队列(BlockingQueue接口类型)
* @param threadFactory 线程工厂 用于创建线程
* @param RejectedExecutionHandler 拒绝策略 直接抛异常
*线程不是越多越好,google工程师推荐 线程个数=cpu核心数+1(例如四核的开5个线程最好)
* */
// 参数任务上限
LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(1000);
ThreadFactory threadFactory = new ThreadFactory() {
// int i = 0; 用并发安全的包装类
AtomicInteger atomicInteger = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
//创建线程 吧任务传进来
Thread thread = new Thread(r);
// 给线程起个名字
thread.setName("MyThread" + atomicInteger.getAndIncrement());
return thread;
}
};
ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 1200L,
TimeUnit.SECONDS, blockingQueue, threadFactory,new ThreadPoolExecutor.AbortPolicy());
pool.execute(new Runnable() {
@Override
public void run() {
//查询全部数量
map.put("all",all);
pool.shutdown();
}
});
pool.execute(new Runnable() {
@Override
public void run() {
//查询我发起的数量
map.put("started",started);
pool.shutdown();
}
});
pool.execute(new Runnable() {
@Override
public void run() {
//查询已办数量
map.put("done",done);
pool.shutdown();
}
});
pool.execute(new Runnable() {
@Override
public void run() {
//按类型查询数量
pool.shutdown();
}
});
pool.execute(new Runnable() {
@Override
public void run() {
//查询审批速度
pool.shutdown();
}
});
//我的需求是等待所有线程任务都执行完毕后,统一返回结果,所以需要等待1分钟等所有线程执行完毕,1分钟还没执行完就抛异常
pool.awaitTermination(1, TimeUnit.MINUTES);
result.put("lable",lable);
result.putAll(map);
return result;
}