1.创建线程池
package org.example.util; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.scheduling.annotation.EnableAsync; import java.util.concurrent.*; @EnableAsync @Configurable public class ThreadPoolConfig { // 最大线程数-视情况而定 private static final int MAX_POOL_SIZE = 30; // CPU核数*2+1 = 核心线程数 Runtime.getRuntime().availableProcessors() private static final int CORE_POOL_SIZE = 5 * 2 + 1; private static final int QUEUE_CAPACITY = 100; // 线程数大于核心线程数,多余的空闲线程的存活最长时间 private static final Long KEEP_ALIVE_TIME = 1L; /** * 定义公共线程池 */ public static ThreadPoolExecutor threadPool = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY), new ThreadFactoryBuilder() .setNameFormat("threadPool" + "-%d") .setDaemon(true).build(), new ThreadPoolExecutor.CallerRunsPolicy()); public static void execute(Runnable command){ threadPool.execute(command); } }
2.创建单线程
package org.example.config; import lombok.extern.slf4j.Slf4j; import org.example.service.IUsermessageService; import java.util.Date; import java.util.concurrent.TimeUnit; @Slf4j public class ActivationThreadPool implements Runnable{ private 数据类型1 字段1; private 数据类型2 字段2; public ActivationThreadPool(数据类型1 参数1,数据类型2 参数2){ this.字段1 = 参数1; this.字段2 = 参数2; } public ActivationThreadPool(){ } @Override public void run() { 编写处理任务,根据处理时间,设置线程等待时间... } }
3.设置睡眠等待时间
try {
log.info("假设处理时间200ms,则设置睡眠800ms 睡眠前时间{}",new Date(),);
Thread.sleep(800);
log.info("睡眠后时间{}",new Date());
// "\u001B[31m" 日志变色
} catch (InterruptedException e) {
log.error("线程等待异常!");
e.printStackTrace();
}
3.单线程放入线程池
ThreadPoolConfig.execute(new ActivationThreadPool(参数1,参数2);