赞
踩
使用场景:开发中,经常有一些非主流程业务要处理,为了提升主业务处理速度,可使用线程池来异步处理.例如,开户之后的通知任务.
1,ThreadPoolTaskExecutor
这个类则是spring包下的,是sring为我们提供的线程池类,可以使用基于xml配置的方式创建.
- <bean id="callerRunsPolicy" class="java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy"/>
-
- <!-- 线程池 -->
- <bean id="taskExecutor"
- class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
- <!-- 线程池维护线程的最少数量 -->
- <property name="corePoolSize" value="10"/>
- <!-- 线程池维护线程所允许的空闲时间 -->
- <property name="keepAliveSeconds" value="3000"/>
- <!-- 线程池维护线程的最大数量 -->
- <property name="maxPoolSize" value="100"/>
- <!-- 线程池所使用的缓冲队列 -->
- <property name="queueCapacity" value="200000"/>
- <!-- 阻塞机制 -->
- <property name="rejectedExecutionHandler" ref="callerRunsPolicy"/>
- </bean>
注:ThreadPoolTaskExecutor中的excute和submit方法的区别?
无返回值的任务使用execute方法提交;
有返回值的任务使用submit(Callable) 方法提交
。
使用submit提交任务,提交后只要有从Future取数据的操作,那么主线程在子线程结束后才会结束.
2,ThreadPoolExecutor
这个类是JDK中的线程池类,继承自Executor,里面有一个execute()方法,用来执行线程,线程池主要提供一个线程队列,队列中保存着所有等待状态的线程。
使用方式有两种,可以通过工具类或者构造方法.
- 方式一:构造方法(传入相应的参数即可).
- private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1200), new DiscardOldestPolicy());
- 方式二:通过Executors工具类.
- Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口.
-
- 1、public static ExecutorService newFiexedThreadPool(int Threads)
- 创建固定数目线程的线程池。
-
- 2、public static ExecutorService newCachedThreadPool():
- 创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果没有可用的线程,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
-
- 3、public static ExecutorService newSingleThreadExecutor():
- 创建一个单线程化的Executor。
-
- 4、public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
- 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。