Java -JDK、Spring boot、多线程创建

Java -JDK、Spring boot、多线程创建,第1张

Java -JDK、Spring boot、多线程创建
  • 俗话说 双拳难敌4手,人多好办事;单一个人干活比较吃力的时候,这时我们就需要摇人儿了。
  • 当单线程执行任务效率较低时,我们就考虑使用多线程解决问题,同时注意数据同步问题。

手动创建线程池:

  • 一般建议不丢弃任务,丢弃可能少数据,采用策略 CallerRunsPolicy();返回发起线程继续执行,一般是main 线程
  • 线程池的核心线程数,一般根据CPU 数,以及 阻塞系数确定,0~1,系数越高,执行任务时间越长
  • 分为 IO型、CPU型,根据情况具体配置
	private static final int core= Runtime.getRuntime().availableProcessors();
	private static final int waitCount = 20;

    private static final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor
    			 (core,
    			  core + waitCount, 
    			  60*10, TimeUnit.SECONDS,
                  new ArrayBlockingQueue<>(waitCount),
                  new CustomizableThreadFactory("线程池-"),
            	  new ThreadPoolExecutor.CallerRunsPolicy());

jdk创建,场景一 :

  • 执行较多耗时任务,不需要实时刷新状态,任务完成修改数据状态,前端查询更新
  • 这里都是,比如接口调用一次,执行到多线程调用,就会往线程池添加一个执行任务线程,或者由空闲线程接手
//不需要返回值异步执行时
pool.execute(() -> {
            materialService.toConvertForAdd(trainInformation);
            esHandle(trainInformation);
});
//需要返回值时
Callable c1 = ()-> exampleServcie.cleanHouse(1);
Callable c2 = ()-> exampleServcie.cleanHouse(2);
Callable c3 = ()-> exampleServcie.cleanHouse(3);
Callable c4 = ()-> exampleServcie.cleanHouse(4);
List> futures = poolExecutor.invokeAll(Arrays.asList(c1, c2, c3, c4));
futures.forEach(e->{
    try {
        System.out.println(e.get());
    } catch (InterruptedException | ExecutionException ex) {
        ex.printStackTrace();
    }
});

Spring boot 工具类运用

  • ThreadPoolTaskExecutor
@EnableAsync
@Configuration
public class PoolConfig {

    
    private static final int CORE = Runtime.getRuntime().availableProcessors();

    
    @Bean("cpuDefaultThreadPool")
    public Executor cpuDefaultThreadPool(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(CORE+1);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.setMaxPoolSize(CORE+21);
        taskExecutor.setKeepAliveSeconds(60*10);
        taskExecutor.setThreadNamePrefix("cpuPool-");
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.initialize();
        return taskExecutor;
    }

    
    @Bean("ipDefaultThreadPool")
    public Executor ipDefaultThreadPool(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        double blockingCoefficient =0.9;
        int poolSize = (int) (CORE / (1- blockingCoefficient));
        taskExecutor.setCorePoolSize(poolSize);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.setMaxPoolSize(poolSize+20);
        taskExecutor.setKeepAliveSeconds(60*30);
        taskExecutor.setThreadNamePrefix("ioPool-");
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.initialize();
        return taskExecutor;
    }

}
@Async("cpuDefaultThreadPool")
CompletableFuture cleanHouseAsync(Integer range);
@Override
public CompletableFuture cleanHouseAsync(Integer range) {
    try {
        Thread.sleep(1000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    log.info("Async: 打扫完了"+range+"号房间");
    return CompletableFuture.completedFuture(true);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5686784.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存