JDK執行緒池和Spring執行緒池的使用例項解析
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了JDK執行緒池和Spring執行緒池的使用例項解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
JDK執行緒池和Spring執行緒池例項,非同步呼叫,可以直接使用
(1)JDK執行緒池的使用,此處採用單例的方式提供,見示例:
public class ThreadPoolUtil { private static int corePoolSize = 5; private static int maximumPoolSize = 10; private static long keepAliveTime = 60L; private static TimeUnit unit = TimeUnit.SECONDS; private static int capacity = 1024; private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jdk-thread-pool-%d").build(); private static final ExecutorService executorService = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,new LinkedBlockingQueue<>(capacity),namedThreadFactory,new ThreadPoolExecutor.AbortPolicy()); private ThreadPoolUtil () { } public static ExecutorService getExecutorService () { return executorService; } }
在其它地方可以直接這樣使用:
ThreadPoolUtil.getExecutorService().execute(() -> { System.out.println("test1"); System.out.println("test2"); } )
(2)Spring執行緒池的使用,此處通過配置類的方式配置執行緒池的相關屬性,見示例:
@Configuration @EnableAsync public class DocataThreadBeanConfig { private int corePoolSize = 5; private int maxPoolSize = 10; private int queueCapacity = 1024; private String namePrefix = "async-service-task-"; // 上述屬性可以通過@Value來讀取配置值 @Bean(name = "asyncServiceTaskExecutor") public TaskExecutor asyncServiceExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 設定核心執行緒數 executor.setCorePoolSize(corePoolSize); // 設定最大執行緒數 executor.setMaxPoolSize(maxPoolSize); // 設定佇列容量 executor.setQueueCapacity(queueCapacity); // 設定執行緒活躍時間(秒) executor.setKeepAliveSeconds(60); // 設定預設執行緒名稱 executor.setThreadNamePrefix(namePrefix); // 設定拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任務結束後再關閉執行緒池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize(); ; return executor; } }
在其它檔案中需要這樣使用:
@Resource(name="asyncServiceTaskExecutor") private ThreadPoolTaskExecutor asyncServiceTaskExecutor;
不要直接使用@Autowired,否則會提示失敗的
@Autowired private ThreadPoolTaskExecutor asyncServiceTaskExecutor;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。