Java普通线程池记录

纯Java线程池记录及使用

package com.zhx.gdp.common.threadPool;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
public class MyThreadPool extends ThreadPoolTaskExecutor {

    @Nullable
    ThreadPoolExecutor threadPoolExecutor;

    //核心线程数
    int corePoolSize = 2;
    //最大线程数
    int maximumPoolSize = 10;
    //最大空闲时间
    long keepAliveTime = 5;
    /*
    时间单位
        TimeUnit.DAYS:天
        TimeUnit.HOURS:小时
        TimeUnit.MINUTES:分
        TimeUnit.SECONDS:秒
        TimeUnit.MILLISECONDS:毫秒
        TimeUnit.MICROSECONDS:微妙
        TimeUnit.NANOSECONDS:纳秒
     */
    TimeUnit unit = TimeUnit.MINUTES;
    /*
    阻塞队列类型
        ArrayBlockingQueue:一个由数组结构组成的有界阻塞队列。
        LinkedBlockingQueue:一个由链表结构组成的有界阻塞队列。
        SynchronousQueue:一个不存储元素的阻塞队列,即直接提交给线程不保持它们。
        PriorityBlockingQueue:一个支持优先级排序的无界阻塞队列。
        DelayQueue:一个使用优先级队列实现的无界阻塞队列,只有在延迟期满时才能从中提取元素
        LinkedTransferQueue:一个由链表结构组成的无界阻塞队列。与SynchronousQueue类似,还含有非阻塞方法。
        LinkedBlockingDeque:一个由链表结构组成的双向阻塞队列。
     */
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(20);
    /*
        线程工厂 Executors.defaultThreadFactory(),也可以使用下面的
     */
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNamePrefix("gdp-web_%d").build();
    /*
    拒绝策略
        AbortPolicy:拒绝并抛出异常。
        CallerRunsPolicy:使用当前调用的线程来执行此任务。
        DiscardOldestPolicy:抛弃队列头部(最旧)的一个任务,并执行当前任务。
        DiscardPolicy:忽略并抛弃当前任务。
     */
    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    public ThreadPoolExecutor getThreadPoolExecutor() {
        new ThreadPoolTaskExecutor();
        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

        return threadPoolExecutor;
    }
}

yaml配置

spring:
  #spring 线程池参数配置
  task:
    execution:
      #设置线程名字的前缀
      thread-name-prefix: gdp_thread_
      pool:
        #设置核心线程数
        core-size: 1
        #设置最大线程数
        max-size: 100
        #设置线程的最大空闲时间
        keep-alive: 60
        #设置缓冲队列大小
        queue-capacity: 100
        #是否允许核心线程超时
        allow-core-thread-timeout: true
        #拒绝策略  AbortPolicy:拒绝并抛出异常。
        #        CallerRunsPolicy:使用当前调用的线程来执行此任务。
        #        DiscardOldestPolicy:抛弃队列头部(最旧)的一个任务,并执行当前任务。
        #        DiscardPolicy:忽略并抛弃当前任务。
        rejected-execution-handler: CallerRunsPolicy


import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
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.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@EnableAsync
@Configuration
public class ThreadPoolConfig implements AsyncConfigurer {

    private static final String EXECUTOR_NAME = "asyncExecutor";

    @Value("${task.execution.pool.core-size}")
    private Integer corePoolSize;
    @Value("${task.execution.pool.max-size}")
    private Integer maxPoolSize;
    @Value("${task.execution.pool.queue-capacity}")
    private Integer queueCapacity;
    @Value("${task.execution.thread-name-prefix}")
    private String threadNamePrefix;
    @Value("${task.execution.pool.rejected-execution-handler}")
    private String rejectedExecutionHandler;

    @Bean(name = EXECUTOR_NAME)
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        // 阻塞队列容量
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        // 待任务在关机时完成--表明等待所有线程执行完
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(getRejectedExecutionHandler(rejectedExecutionHandler));

        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }


    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, obj) -> {
            log.error("[ThreadPool Exception]:Message [{}], Method [{}]", throwable.getMessage(), method.getName());
            for (Object param : obj) {
                log.error("Parameter value [{}] ", param);
            }
        };
    }

    /**
     * 根据传入的参数获取拒绝策略
     * @param rejectedName 拒绝策略名,比如 CallerRunsPolicy
     * @return RejectedExecutionHandler 实例对象,没有匹配的策略时,默认取 CallerRunsPolicy 实例
     */
    public RejectedExecutionHandler getRejectedExecutionHandler(String rejectedName){
        Map<String, RejectedExecutionHandler> rejectedExecutionHandlerMap = new HashMap<>(16);
        rejectedExecutionHandlerMap.put("CallerRunsPolicy", new ThreadPoolExecutor.CallerRunsPolicy());
        rejectedExecutionHandlerMap.put("AbortPolicy", new ThreadPoolExecutor.AbortPolicy());
        rejectedExecutionHandlerMap.put("DiscardPolicy", new ThreadPoolExecutor.DiscardPolicy());
        rejectedExecutionHandlerMap.put("DiscardOldestPolicy", new ThreadPoolExecutor.DiscardOldestPolicy());
        return rejectedExecutionHandlerMap.getOrDefault(rejectedName, new ThreadPoolExecutor.CallerRunsPolicy());
    }
}

链接的文章非常好
使用及详细学习参考

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值