1. 程式人生 > 其它 >springboot自義定執行緒池

springboot自義定執行緒池

在boot專案中新增一個自定義執行緒池的配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean
    
public ThreadPoolTaskExecutor myThreadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //此方法返回可用處理器的虛擬機器的最大數量; // int core = Runtime.getRuntime().availableProcessors(); int core = 30; //設定核心執行緒數 executor.setCorePoolSize(core);
//設定最大執行緒數 executor.setMaxPoolSize(core * 10 + core); //除核心執行緒外的執行緒存活時間 executor.setKeepAliveSeconds(3); //緩衝佇列 executor.setQueueCapacity(core); executor.setThreadNamePrefix("thread-execute"); //設定拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor; }

在啟動類上新增@EnableAsync註解開啟多執行緒

 方法上面@Async("myThreadPoolTaskExecutor") 指定使用那個執行緒池配置,不然會使用spring預設的執行緒池

也可以自己在使用執行緒時指定對應的執行緒池,CompletableFuture這個工具包提供方法還是挺多,不過這個就需要慢慢去探索啦!

public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                sum += i;
            }
            return sum;
        },myThreadPoolTaskExecutor); 
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> { 

      try {
        Thread.sleep(
1000);
      }
catch (InterruptedException e) {
         e.printStackTrace();
      }

      return 1;
    },
myThreadPoolTaskExecutor);
    CompletableFuture.allOf(future1, future2); 
    System.
out.println(future1.get() + future2.get());
  }