有了多线程异步执行,可以把耗时的操作都留给线程池中的线程去异步执行,在主线程中和前端保持连接,防止前端一直等待造成页面无法操作,甚至无响应。
https://msd.misuland.com/pd/3255817963235712406
简单一点的,这样:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
public class Job {
private static Logger logger = LoggerFactory.getLogger(Job.class);
ExecutorService fixedThreadPool =null;
//线程池大小
private static final int THREAD_COUNT = 10;
@Autowired
private TaskService taskService;
public void start() {
//Runtime.getRuntime().availableProcessors()+1
fixedThreadPool = Executors.newFixedThreadPool(THREAD_COUNT);
for(;;){
try {
//获取当前活动的线程数
int threadCount = ((ThreadPoolExecutor)fixedThreadPool).getActiveCount();
// logger.info("active thread count:{}",threadCount);
if(threadCount < THREAD_COUNT) {
MyTask task = taskService.getOneTaskForRunning();
if(task !=null){
logger.info("get a task:"+task .toString());
fixedThreadPool.execute(new TaskJob(task));
}
}
Thread.sleep(1*5*1000);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}
}
public void shutdown(){
if(fixedThreadPool!=null){
fixedThreadPool.shutdown();
}
}
private class TaskJob implements Runnable{
private MyTask yask;
TaskJob(MyTask task){
this.task = task;
}
@Override
public void run() {
try{
/**逻辑**/
}catch (Exception ex){
logger.error(ex.getMessage(),ex);
}
}
}
}