国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 網(wǎng)站 > 幫助中心 > 正文

JDK線程池和Spring線程池的使用實(shí)例解析

2024-07-09 22:42:04
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

這篇文章主要介紹了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)之家。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沁阳市| 昌黎县| 华池县| 松滋市| 剑阁县| 临桂县| 疏附县| 中山市| 卢氏县| 台南县| 烟台市| 永靖县| 徐闻县| 宁安市| 天津市| 清河县| 陇南市| 桃江县| 阿拉善盟| 黄骅市| 堆龙德庆县| 阿图什市| 吴川市| 玛沁县| 巢湖市| 绵竹市| 武乡县| 天长市| 三台县| 武陟县| 崇明县| 铜山县| 特克斯县| 澄江县| 福贡县| 来宾市| 曲周县| 集安市| 周至县| 江孜县| 女性|