Spring线程池与JDK线程池配置

    //直接在代码中使用
	public static void main(String[] args) throws InterruptedException, ExecutionException {
	    //JDK线程池示例
		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		CompletionService<String> executor = new ExecutorCompletionService<String>(threadPool);
		Future<String> future = executor.submit(new TaskHandle());
		System.out.println(future.get());
		threadPool.shutdown();
		
		//Spring线程池示例
		FutureTask<String> ft = new FutureTask<String>(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的配置文件中:
		 * <!-- 配置线程池 -->  
			<bean id ="taskExecutor"  class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >  
    		<!-- 线程池维护线程的最少数量 -->  
			<span style="white-space:pre">  </span><property name ="corePoolSize" value ="5" />  
    		<!-- 线程池维护线程所允许的空闲时间 -->  
			<span style="white-space:pre">  </span><property name ="keepAliveSeconds" value ="5" />  
    		<!-- 线程池维护线程的最大数量 -->  
			<span style="white-space:pre">  </span><property name ="maxPoolSize" value ="10" />  
    		<!-- 线程池所使用的缓冲队列 -->  
			<span style="white-space:pre">  </span><property name ="queueCapacity" value ="10" />  
			</bean> 
		 * 
		 */
		
		//在程序中这样调用方法
		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<String> {

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

 

转载于:https://my.oschina.net/u/2391658/blog/691272

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值