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();
		}
	}
相關文章
相關標籤/搜索