最近有一个需求, 前端点击一个按钮, 后端需要多线程执行任务, 执行完返回结果到前端. 使用线程池实现, 每次调用新建线程池对象, 使用完销毁线程池对象, 这个用的是 spring 线程池, java 自带的线程池效果差不多, 代码如下:
实现代码:
public String testThreadPool() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = ThreadPoolUtils.getThreadPool();
// 开启 50 个线程
for (int i = 1; i <= 50; i++) {
int index = i;
threadPoolTaskExecutor.execute(new Thread(new Runnable() {@Override public void run() {
//TODO 处理业务
System.out.println(index);
}
}));
}
while (true) {
//sleep 2 秒
try {
Thread.sleep(200);
} catch(InterruptedException e) {
e.printStackTrace();
}
// 如果活跃的线程为 0, 则说明任务处理完毕
if (threadPoolTaskExecutor.getActiveCount() < 1) {
System.out.println("结束了!");
// 销毁线程池
threadPoolTaskExecutor.destroy();
break;
}
}
return "任务处理完毕!";
}
生成线程池的类:
package capital.core.utils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 线程池 util
* @author tanqian
* @date 2018 年 1 月 30 日
*/
public class ThreadPoolUtils {
/**
* 返回一个初始化完成的线程池对象
* @return
*/
public static ThreadPoolTaskExecutor getThreadPool() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 最小线程数
threadPoolTaskExecutor.setCorePoolSize(20);
// 最大线程数
threadPoolTaskExecutor.setMaxPoolSize(50);
// 空闲线程存活时间
threadPoolTaskExecutor.setKeepAliveSeconds(1000);
// 队列中最大线程
threadPoolTaskExecutor.setQueueCapacity(50);
// 初始化
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
来源: http://blog.csdn.net/tanqian351/article/details/79220308