springboot 多线程的使用
阅读原文时间:2023年07月08日阅读:2

int pageSize = 10000;
int totalCount = doctorDAO.selectDatasByMapCount2(jsonArray, false, null);
int m = totalCount % pageSize;
int pageCount = m == 0 ? (totalCount / pageSize) : (totalCount / pageSize + 1);

     List<DoctorDO> resultList = new ArrayList<>();  
     BlockingQueue<Future<List<DoctorDO>>> queue = new LinkedBlockingQueue<>();

     for (int i = 0; i < pageCount; i++) {  
         Thread.sleep(0);  
         Future<List<DoctorDO>> future;  
         future = queryDatas(jsonArray, i \* pageSize, pageSize);  
         queue.add(future);  
     }

     int queueSize = queue.size();  
     logger.debug("queue size:" + queueSize);  
     for (int i = 0; i < queueSize; i++) {  
         List<DoctorDO> subAttendList = queue.take().get();  
         if (!CollectionUtils.isEmpty(subAttendList)) {  
             resultList.addAll(subAttendList);  
         }  
     }

 @Async  
 public Future<List<DoctorDO>> queryDatas(JSONArray jsonArray, int start, int size) {  
     List<DoctorDO> subAttendList = doctorDAO.selectDatasByMap2(start, size, jsonArray, true, null);  
     logger.info("完成任务");  
     return new AsyncResult<>(subAttendList);  
 }

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
* 多线程配置类
*/
@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
private static Logger logger = LoggerFactory.getLogger(ThreadConfig.class);

 /\*\*  
  \* The {@link Executor} instance to be used when processing async  
  \* method invocations.  
  \*/  
 @Override  
 public Executor getAsyncExecutor() {  
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
     executor.setCorePoolSize(15);  
     executor.setMaxPoolSize(25);  
     executor.setQueueCapacity(25);  
     executor.initialize();  
     return executor;  
 }

 /\*\*  
  \* The {@link AsyncUncaughtExceptionHandler} instance to be used  
  \* when an exception is thrown during an asynchronous method execution  
  \* with {@code void} return type.  
  \*/  
 @Override  
 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {  
     return new SpringAsyncExceptionHandler();  
 }

 class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {  
     @Override  
     public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {  
         throwable.printStackTrace();  
     }  
 }

 public static void main(String\[\] args) {  
     logger.info("123");  
     logger.info("123");  
     logger.info("123");  
 }  

}