//直接在代码中使用 public static void main(String[] args) throws InterruptedException, ExecutionException { //JDK线程池示例 ExecutorService threadPool = Executors.newFixedThreadPool(5); CompletionServiceexecutor = 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(); } }