這篇文章主要介紹了JDK線程池和Spring線程池的使用實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
JDK線程池和Spring線程池實(shí)例,異步調(diào)用,可以直接使用
(1)JDK線程池的使用,此處采用單例的方式提供,見(jiàn)示例:
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線程池的使用,此處通過(guò)配置類(lèi)的方式配置線程池的相關(guān)屬性,見(jiàn)示例:
@Configuration@EnableAsyncpublic class DocataThreadBeanConfig { private int corePoolSize = 5; private int maxPoolSize = 10; private int queueCapacity = 1024; private String namePrefix = "async-service-task-"; // 上述屬性可以通過(guò)@Value來(lái)讀取配置值 @Bean(name = "asyncServiceTaskExecutor") public TaskExecutor asyncServiceExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 設(shè)置核心線程數(shù) executor.setCorePoolSize(corePoolSize); // 設(shè)置最大線程數(shù) executor.setMaxPoolSize(maxPoolSize); // 設(shè)置隊(duì)列容量 executor.setQueueCapacity(queueCapacity); // 設(shè)置線程活躍時(shí)間(秒) executor.setKeepAliveSeconds(60); // 設(shè)置默認(rèn)線程名稱(chēng) executor.setThreadNamePrefix(namePrefix); // 設(shè)置拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任務(wù)結(jié)束后再關(guān)閉線程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize(); ; return executor; }}
在其它文件中需要這樣使用:
@Resource(name="asyncServiceTaskExecutor")private ThreadPoolTaskExecutor asyncServiceTaskExecutor;
不要直接使用@Autowired,否則會(huì)提示失敗的
@Autowiredprivate ThreadPoolTaskExecutor asyncServiceTaskExecutor;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)之家。
新聞熱點(diǎn)
疑難解答
圖片精選