在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(); } }
版权声明:本文为feiyang123_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。