在使用Thread的时候总是被提示,要求使用线程池。所以就研究一下怎么在springboot上面配置线程池吧!
新建一个threadpool的springboot项目(此为代码完成后的项目结构)
使用到的注解为
@Configuration:用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@EnableAsync:表示项目支持异步方法调用。
@Async:表示该方法为异步方法,即该方法和调用者不在一个线程中进行。
编写线程池的配置文件,命名为BeanConfig.java
package com.zhouxiaoxi.threadpool.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author zhouzhaodong
*/
@Configuration
@EnableAsync
public class BeanConfig {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(10);
// 设置最大线程数
executor.setMaxPoolSize(20);
// 设置队列容量
executor.setQueueCapacity(50);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("hello-");
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
写一个service接口用来实现高并发场景:
package com.zhouxiaoxi.threadpool.service;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhouzhaodong
*/
public interface TestService {
/**
* 测试方法
*/
void test(AtomicInteger atomicInteger);
}
实现该接口
package com.zhouxiaoxi.threadpool.service.impl;
import com.zhouxiaoxi.threadpool.service.TestService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhouzhaodong
*/
@Service
public class TestServiceImpl implements TestService {
@Override
@Async("taskExecutor")
public void test(AtomicInteger atomicInteger) {
int num = 0;
//如果atomicInteger大于0的话
while (atomicInteger.get() > 0){
//atomicInteger就执行减一的操作
atomicInteger.decrementAndGet();
num ++;
}
System.out.println(num);
}
}
新建一个test方法来调用接口
package com.zhouxiaoxi.threadpool;
import com.zhouxiaoxi.threadpool.service.TestService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;
@SpringBootTest
class ThreadPoolTest {
@Resource
TestService testService;
@Test
void contextLoads() {
}
@Test
void test() {
AtomicInteger atomicInteger = new AtomicInteger(10000);
int num = 10;
for (int i = 0; i < num; i++) {
testService.test(atomicInteger);
}
}
}
输出结果为
1439
0
1487
1510
628
820
1467
1019
343
1291
这就说明调用了10个接口,我们写的线程池应用成功了。