Spring线程池与JDK线程池配置

本文通过示例代码对比了Spring线程池与JDK线程池的使用方式,介绍了如何在Spring环境中配置和使用线程池,并展示了如何通过Spring的注入功能简化线程池任务的执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在web开发项目中,处理任务的线程池或多或少会用到。如果项目中使用到了spring,使用线程池时就可以直接使用spring自带的线程池了。下面是Spring线程池与JDK线程池的使用实例,做个参考吧。

//直接在代码中使用
	public static void main(String[] args) throws InterruptedException, ExecutionException {
	    //JDK线程池示例
		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		CompletionService executor = new ExecutorCompletionService(threadPool);
		Future future = executor.submit(new TaskHandle());
		System.out.println(future.get());
		threadPool.shutdown();
		
		//Spring线程池示例
		FutureTask ft = new FutureTask(new TaskHandle());
		ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
		poolTaskExecutor.setQueueCapacity(10);
		poolTaskExecutor.setCorePoolSize(5);
		poolTaskExecutor.setMaxPoolSize(10);
		poolTaskExecutor.setKeepAliveSeconds(5);
		poolTaskExecutor.initialize();
		
		poolTaskExecutor.submit(ft);
		System.out.println(ft.get());
		poolTaskExecutor.shutdown();
		
		/**
		 * 把以下配置加到spring的配置文件中:
		 *   
			  
    		  
			    
    		  
			    
    		  
			    
    		  
			    
			 
		 * 
		 */
		
		//在程序中这样调用方法
		ApplicationContext ctx =  new ClassPathXmlApplicationContext("applicationContext.xml");
		ThreadPoolTaskExecutor contextPoolTaskExecutor = (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
		System.out.println(contextPoolTaskExecutor.getActiveCount());
		
		//如果启用了spring的注入功能,则可以在被spring管理的bean方法上添加“@Async”即可。
	}
	
	/**
	 * 处理任务的类,为了方便大家观看,我把这个类写到当前类中了。
	 * @author mengfeiyang
	 *
	 */
	private static class TaskHandle implements Callable {

		public String call() throws Exception {
			
			return Thread.currentThread().getName();
		}
	}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值