Spring Boot2.x 使用多线程

  • 关于Spring Boot多线程
    Spring是通过任务执行器(TaskExecutor)来实现多线程和并发编程,使用ThreadPoolTaskExecutor来创建一个基于线城池的TaskExecutor。在使用线程池的大多数情况下都是异步非阻塞的。我们配置注解@EnableAsync可以开启异步任务。然后在实际执行的方法上配置注解@Async上声明是异步任务。
  • 配置类代码如下
    • 利用EnableAsync来开启Springboot对于异步任务的支持
    • 配置类实现接口AsyncConfigurator,返回一个ThreadPoolTaskExecutor线程池对象。
import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {

    /**
     * The {@link Executor} instance to be used when processing async
     * method invocations.
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(15);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }

    /**
     * The {@link AsyncUncaughtExceptionHandler} instance to be used
     * when an exception is thrown during an asynchronous method execution
     * with {@code void} return type.
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

  • 任务执行
    • 通过@Async注解表明该方法是异步方法,如果注解在类上,那表明这个类里面的所有方法都是异步的。
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {
    @Async
    public void executeAsyncTask(int i) {
        System.out.println("Thread" + Thread.currentThread().getName() + " run:" + i);
    }
}
  • 测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class ThreadApplicationTests {

	@Autowired
    private AsyncTaskService asyncTaskService;

    @Test
    public void contextLoads() {
    }

    @Test
    public void threadTest() {
        for (int i = 0; i < 5; i++) {
            asyncTaskService.executeAsyncTask(i);
        }
    }
}
  • 输出
ThreadThreadPoolTaskExecutor-1 run:0
ThreadThreadPoolTaskExecutor-5 run:4
ThreadThreadPoolTaskExecutor-4 run:3
ThreadThreadPoolTaskExecutor-2 run:1
ThreadThreadPoolTaskExecutor-3 run:2

你可能感兴趣的:(Spring/Spring,Boot)