springboot新建線程池


一、使用ThreadPoolTaskExecutor創建線程池

這個類則是spring包下的,是sring為我們提供的線程池類

1、線程詞配置類

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

// 線程詞配置類
@Configuration
//開啟異步調用, 即哪個方法用了 @Async("taskExecutor"),就會通過線程池調用
@EnableAsync
public class TaskPoolConfig {

    @Bean(name="taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心線程數:就是線程池中的核心線程數量,這幾個核心線程,只是在沒有用的時候,也不會被回收
        executor.setCorePoolSize(6);
        //配置最大線程數:就是線程池中可以容納的最大線程的數量
        executor.setMaxPoolSize(20);
        //配置隊列大小
        executor.setQueueCapacity(300);
        //線程池維護線程所允許的空閑時間:就是線程池中除了核心線程之外的其他的最長可以保留的時間,因為在線程池中,除了核心線程即使在無任務的情況下也不能被清除,其余的都是有存活時間的,意思就是非核心線程可以保留的最長的空閑時間
        executor.setKeepAliveSeconds(60);
        //配置線程池中的線程的名稱前綴
        executor.setThreadNamePrefix("task-executor-");

        // handler,是一種拒絕策略,我們可以在任務滿了之后,拒絕執行某些任務。
        // rejection-policy:當pool已經達到max size的時候,如何處理新任務
        // CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // AbortPolicy:用於被拒絕任務的處理程序,它將拋出RejectedExecutionException
        // CallerRunsPolicy:用於被拒絕任務的處理程序,它直接在execute方法的調用線程中運行被拒絕的任務。
        // DiscardOldestPolicy:用於被拒絕任務的處理程序,它放棄最舊的未處理請求,然后重試execute。
        // DiscardPolicy:用於被拒絕任務的處理程序,默認情況下它將丟棄被拒絕的任務。
        
        //執行初始化
        executor.initialize();
        return executor;
    }
}

2、使用

顯式使用:

    @Autowired
    @Qualifier("taskExecutor")  //指定某個bean
    private Executor taskExecutor;

    // 顯式調用線程池
    @GetMapping("testPool")
    @ApiOperation(value = "查找",notes = "顯式調用線程池的線程,異步執行方法")
    public ResponseResult testPool() {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 20; i++) {
                        Thread.sleep(200);
                        System.out.println("異步執行testPool(),  i = " + i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        return ResponseResult.success("后台在執行中,先返回數據給你");
    }

隱式使用:

@Async("taskExecutor")    // 這個注解是將此方法交給線程池里的線程來運行
    public void testThreadPool() {
        try {
            Thread.sleep(1000);
            System.out.println(" 多線程執行 " + currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

// 異步也可以返回Future內容,Future.get()可以取出future里的內容
    @Async
    public Future<String> asyncInvokeReturnFuture(int i) {
    Future<String> future;
    try {
        Thread.sleep(1000 * 1);
        future = new AsyncResult<String>("success:" + i);
    } catch (InterruptedException e) {
        future = new AsyncResult<String>("error");
    }
    return future;

 

二、直接使用原生線程池 

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) ;

ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 20, 2,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(5),new ThreadPoolExecutor.CallerRunsPolicy());

 

三、Executors工廠方法創建線程池(少用)

 

//創建使用單個線程的線程池
        ExecutorService es1 = Executors.newSingleThreadExecutor();

//創建使用固定線程數的線程池
        ExecutorService es2 = Executors.newFixedThreadPool(3);

 //創建一個會根據需要創建新線程的線程池
        ExecutorService es3 = Executors.newCachedThreadPool();

 //創建擁有固定線程數量的定時線程任務的線程池
        ScheduledExecutorService es4 = Executors.newScheduledThreadPool(2);

//創建只有一個線程的定時線程任務的線程池
        ScheduledExecutorService es5 = Executors.newSingleThreadScheduledExecutor();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM