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個任務不需要等待其他方法執行完,才去執行自己的任務
這就是異步的場景,這種場景下就可以使用多線程