您的位置:首页 > 编程语言 > Java开发

java线程池管理多线程的应用

2018-01-31 17:54 176 查看
最近有一个需求,前端点击一个按钮,后端需要多线程执行任务,执行完返回结果到前端。使用线程池实现,每次调用新建线程池对象,使用完销毁线程池对象,这个用的是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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程池