国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 锦屏县| 西盟| 无为县| 电白县| 淮安市| 额尔古纳市| 乌兰察布市| 许昌市| 宁城县| 府谷县| 宁武县| 洛宁县| 金川县| 开平市| 兖州市| 平原县| 定远县| 广平县| 萨迦县| 高邮市| 汕尾市| 和田县| 通河县| 九寨沟县| 双城市| 青冈县| 修武县| 五华县| 延安市| 报价| 无锡市| 容城县| 安塞县| 天门市| 郎溪县| 新巴尔虎左旗| 辽宁省| 宝山区| 怀远县| 金川县| 华亭县|