1.使用springboot自帶的異步
1. 在啟動類中開啟異步
加上注解:
@EnableAsync
2. 異步的類上需要加@Component,如果這個類是異步的話需要在類上加@Async
如果某個方法是則只需要在方法上加上注解
3.注意點:
1)要把異步任務封裝到類里面,不能直接寫到Controller
2)增加Future<String> 返回結果 AsyncResult<String>("task執行完成");
3)如果需要拿到結果 需要判斷全部的 task.isDone()
4) @Async使用,必須是public方法 必須是非static方法,如果返回報錯則是環繞增強的問題,需要返回對象,如Object
2.使用線程池異步
1. ThreadPoolUtils 工具類

import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolUtils { private static volatile ThreadPoolExecutor pool = null; public static ThreadPoolExecutor getThreadPool() { if (pool == null) { synchronized (ThreadPoolUtils.class) { if (pool == null) { pool = createPool(10, 100); } } } return pool; } /** * 創建線程池 * * @param corePoolSize 核心線程數量 * @param maxThreadSize 最大線程數 * @return */ private static ThreadPoolExecutor createPool(int corePoolSize, int maxThreadSize) { return new ThreadPoolExecutor(corePoolSize, maxThreadSize, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } }
2. 使用線程池創建線程

ThreadPoolExecutor threadPool = ThreadPoolUtils.getThreadPool(); threadPool.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return sendEmail("保險產品審核表",emails,"未審核的產品",is); } });
3. threadPool.submit()是可以獲取返回結果的,call方法里返回的數據,
4. Feature feature = submit.get()
submit.get方法是一個阻塞方法,如果開啟的線程內的邏輯沒有處理完成,它會等開啟的線程處理完成。
submit.get(10, TimeUnit.SECONDS)//設置線程的超時時間。