Spring Boot配置多线程(创建线程池、创建线程)

1 Maven依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2 AsyncConfig

多线程配置类。

package com.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

/**
 * 多线程配置类
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    private final TaskExecutionProperties taskExecutionProperties;

    public AsyncConfig(TaskExecutionProperties taskExecutionProperties) {
        this.taskExecutionProperties = taskExecutionProperties;
    }

    /**
     * 创建线程池
     *
     * @return
     */
    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
        //设置最大线程数
        executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
        //线程池所使用的缓冲队列
        executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
        //  线程名称前缀
        executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

    public static class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
            InitializingBean, DisposableBean {

        static final String EXCEPTION_MESSAGE = "Caught async exception";

        private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);

        private final AsyncTaskExecutor executor;

        /**
         * <p>Constructor for ExceptionHandlingAsyncTaskExecutor.</p>
         *
         * @param executor a {@link AsyncTaskExecutor} object.
         */
        public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
            this.executor = executor;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void execute(Runnable task) {
            executor.execute(createWrappedRunnable(task));
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void execute(Runnable task, long startTimeout) {
            executor.execute(createWrappedRunnable(task), startTimeout);
        }

        private <T> Callable<T> createCallable(final Callable<T> task) {
            return () -> {
                try {
                    return task.call();
                } catch (Exception e) {
                    handle(e);
                    throw e;
                }
            };
        }

        private Runnable createWrappedRunnable(final Runnable task) {
            return () -> {
                try {
                    task.run();
                } catch (Exception e) {
                    handle(e);
                }
            };
        }

        /**
         * <p>handle.</p>
         *
         * @param e a {@link Exception} object.
         */
        protected void handle(Exception e) {
            log.error(EXCEPTION_MESSAGE, e);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Future<?> submit(Runnable task) {
            return executor.submit(createWrappedRunnable(task));
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public <T> Future<T> submit(Callable<T> task) {
            return executor.submit(createCallable(task));
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void destroy() throws Exception {
            if (executor instanceof DisposableBean) {
                DisposableBean bean = (DisposableBean) executor;
                bean.destroy();
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void afterPropertiesSet() throws Exception {
            if (executor instanceof InitializingBean) {
                InitializingBean bean = (InitializingBean) executor;
                bean.afterPropertiesSet();
            }
        }
    }
}

3 AsyncTestService

声明异步方法。

package com.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTestService {
    @Async
    public void test(int num) {
        System.out.print("\tnum=" + num);
    }
}

4 调试代码

package com.controller;

import com.service.AsyncTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
    @Autowired
    private AsyncTestService asyncTestService;

    /**
     * 测试多线程
     */
    @GetMapping("/testAsync")
    public void testAsync() {
        for (int i = 0; i < 100; i++) {
            System.out.print("\ti=" + i);
        }
        for (int j = 0; j < 100; j++) {
            asyncTestService.test(j);
        }
        System.out.print("i=" + 1111);
    }
}

5 调试结果

注:

有关调用异步方法创建线程的方式请查看以下博客。

Java 调用@Async异步方法创建线程2种方式(调用外部的异步方法,调用内部的异步方法)_旭东怪的博客-CSDN博客1 Maven依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--hutool工https://blog.csdn.net/qq_38974638/article/details/120348519

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值