1.什么场景下使用线程池?
在异步的场景下,可以使用线程池
不需要同步等待,
不需要管上一个方法是否执行完毕,你当前的方法就可以立即执行
我们来模拟一下,在一个方法里面执行3个子任务,不需要相互等待
2.代码引入线程池配置类
package com.example.demo2.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.concurrent.*;/*** 线程池工具类*/
@Configuration
public class XianChengConfig {/*** 创建线程池放入ioc容器*/@Beanpublic ThreadPoolExecutor threadPoolExecutor(){//核心线程数int corePoolSize = 10;//最大线程数int maximumPoolSize =10;//线程存活时间单位long keepAliveTime = 60;//线程存活时间 秒TimeUnit unit = TimeUnit.SECONDS;//任务队列BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);//线程工厂ThreadFactory threadFactory = Executors.defaultThreadFactory();//拒绝策略 谁调用谁执行RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();ThreadPoolExecutor bean = new ThreadPoolExecutor( corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);return bean;}
}
3.使用线程池
package com.example.demo2.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.ThreadPoolExecutor;@RestController
public class TestController {@Autowiredprivate ThreadPoolExecutor threadPoolExecutor;@GetMapping("/test")public String test() {System.out.println("---------------方法1------------------");threadPoolExecutor.execute(()->{//异步执行 角色任务syncRole();});System.out.println("---------------方法2------------------");threadPoolExecutor.execute(()->{//异步执行 用户任务syncUser();});System.out.println("----------------方法3-----------------");threadPoolExecutor.execute(()->{//异步执行 菜单任务syncMenu();});return "ok";}private void syncRole(){System.out.println("开始获取角色,线程名称:"+Thread.currentThread().getName());try {//阻塞4秒Thread.sleep(1000*4);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("结束获取角色,线程名称:"+Thread.currentThread().getName());}private void syncUser(){System.out.println("开始获取用户,线程名称:"+Thread.currentThread().getName());try {//阻塞3秒Thread.sleep(1000*3);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("结束获取用户,线程名称:"+Thread.currentThread().getName());}private void syncMenu(){System.out.println("开始获取菜单,线程名称:"+Thread.currentThread().getName());try {//阻塞2秒Thread.sleep(1000*2);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("结束获取菜单,线程名称:"+Thread.currentThread().getName());}
}
http://localhost:8080/test
可以看到,角色没有执行完,用户开始执行
用户没有执行完,菜单也开始执行
3个任务不需要等待其他方法执行完,才去执行自己的任务
这就是异步的场景,这种场景下就可以使用多线程