線程池的常規使用:
消息發送類,線程池調用
public class MessageClientSendMsg { /** * 日志記錄器 */ private static final Log LOGGER = new Log(MessageClientSendMsg.class); /** * 線程池 */ private static ExecutorService threadPool; /** * trace */ private String trace; /** * 手機號 */ private String cellNum; /** * 消息實體 */ private MessageProducerReq messageProducerReq; static { threadPool = Executors.newFixedThreadPool(10);//固定個數的線程池 } /** * 構造函數 * * @param trace 請求流水 * @param cellNum 電話號碼 * @param messageProducerReq 消息實體 */ public MessageClientSendMsg(String trace, String cellNum, MessageProducerReq messageProducerReq) { this.trace = trace; this.cellNum = cellNum; this.messageProducerReq = messageProducerReq; } /** * 消息發送 */ public void sendMsg() { SendMsgRunable sendMsgRunable = new SendMsgRunable(); threadPool.execute(sendMsgRunable); } /** * 發送消息內部類並處理異常,不能影響主線程的業務 */ class SendMsgRunable implements Runnable { @Override public void run() { try { MessageClientProducer msgClintProducer = new MessageClientProducer(); msgClintProducer.sendAsyncWithPartition(trace, cellNum, messageProducerReq); } catch (Exception e) { LOGGER.error("消息發送失敗!,trace:" + trace); } } } }
SpringBoot中使用線程池使用@EnableAsync注解和@Async注解
配置線程池:
import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync public class BeanConfig { @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 設置核心線程數 executor.setCorePoolSize(5); // 設置最大線程數 executor.setMaxPoolSize(10); // 設置隊列容量 executor.setQueueCapacity(20); // 設置線程活躍時間(秒) executor.setKeepAliveSeconds(60); // 設置默認線程名稱 executor.setThreadNamePrefix("hello-"); // 設置拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任務結束后再關閉線程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; } }
並發業務:
import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class Test { @Async public void test(int i){ SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss"); try { Thread.sleep(10000); System.out.println("多線程異步執行"+i+" "+Thread.currentThread().getName()+" "+format.format(new Date())); } catch (InterruptedException e) { e.printStackTrace(); } } }
Controller層使用
@GetMapping("/test") @ResponseBody public void test(){ for (int i = 0; i < 100; i++) { test.test(i); } }