您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)如何正確的使用JDK線程池和Spring線程池,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
JDK線程池和Spring線程池實例,異步調(diào)用,可以直接使用
(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線程池的使用,此處通過配置類的方式配置線程池的相關(guān)屬性,見示例:
@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(); // 設(shè)置核心線程數(shù) executor.setCorePoolSize(corePoolSize); // 設(shè)置最大線程數(shù) executor.setMaxPoolSize(maxPoolSize); // 設(shè)置隊列容量 executor.setQueueCapacity(queueCapacity); // 設(shè)置線程活躍時間(秒) executor.setKeepAliveSeconds(60); // 設(shè)置默認(rèn)線程名稱 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,否則會提示失敗的
@Autowired private ThreadPoolTaskExecutor asyncServiceTaskExecutor;
上述就是小編為大家分享的如何正確的使用JDK線程池和Spring線程池了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。