//直接在代码中使用 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(); } }