多线程的异步执行,虽然能大大的提高对计算机资源的利用,但是事情都有两面性,如果控制不好,反而会对系统造成重大影响,从而导致服务不可用。同时大量的线程回收也会给GC增加巨大压力。为了能够重复利用已创建的线程,降低创建和销毁线程的开销,jdk引入了线程池的概念,通俗的讲,当我们需要线程执行任务的时候,从线程池中获取线程,当我们完成任务后也不进行销毁,而将它归还给线程池供他人使用。Springboot也集成了线程池的功能,通过简单的注解就能实现任务的异步执行,下面我们将进行一次使用实践。
环境准备:
- windowns10;
- jdk1.8;
- springboot-2.1.6.RELEASE;
- 开发工具:IntelliJ IDEA;
实践步骤:
1.创建spring-boot项目
用IntelliJ IDEA创建一个springboot的web工程springboot-threadpool,pom.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ruby</groupId>
<artifactId>springboot-threadpool</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-threadpool</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>