之前只是看过线程池的资料,并没有在实际中使用过线程池,今天拿个demo来试下手,理解一下线程池的使用流程:
1.大体的项目结构
2.线程池配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 创建线程池
*/
@EnableAsync
@Configuration
public class TaskExecutePoolConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor poolExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
poolExecutor.setCorePoolSize(5);
// 最大线程数
poolExecutor.setMaxPoolSize(15);
// 队列大小
poolExecutor.setQueueCapacity(100);
// 线程最大空闲时间
poolExecutor.setKeepAliveSeconds(300);
// 拒绝策略
poolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 线程名称前缀
poolExecutor.setThreadNamePrefix("my-pool-");
return poolExecutor;
}
}
3. service层接口
public interface TaskExcuteService {
void testExecutor(String str);
}
4.实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@Service
public class TaskExcuteServiceImpl implements TaskExcuteService{
@Qualifier("taskExecutor")
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Override
public void testExecutor(String str) {
for (int i = 0; i < 10; i++) {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--" + str);
}
});
}
}
}
5.再写个接口调用实现
import com.example.threadpool.service.TaskExcuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class test{
@Autowired
private TaskExcuteService service;
@RequestMapping("/hello")
public void testExecutor(final String str) {
service.testExecutor("aaa");
}
}
6.看结果:
7.分析
7.1 配置的核心线程数是5,循环提交了10个任务,中间睡3秒,所以每次会打印5条消息,2次打印完.
7.2 Service层导入的线程池实现,对应的Config里面的bean类名
3.excute 方法,我理解只是向线程池里面提交任务,等待线程池来执行