多线程控制每秒并发量

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值