好长时间没记录下了,又是一周,随便写写最近的疑惑。部门大哥在项目里用到了线程池,既然接触到了我也就大概查了些资料。由于项目中用到的是Spring中的线程池
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor,在Spring.xml中配置如下:
<bean id="TaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 线程名称前缀 -->
<property name="threadNamePrefix" value="[A-Sync-Thread]-" />
<!-- 核心线程数 -->
<property name="corePoolSize" value="3" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="5" />
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="1" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="3000" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略,调用者的线程会执行该任务,如果执行器已关闭,则丢弃. -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
java从jdk1.5后引入了一个并发工具包concurrent,其中Executors类中提供了4种初始化的线程池。
ExecutorService ThreadPool0 = Executors.newCachedThreadPool();//无边界线程池,如果任务过多,会降低系统性能
ExecutorService ThreadPool1 = Executors.newFixedThreadPool(3);//固定线程池
ExecutorService ThreadPool2 = Executors.newSingleThreadExecutor();//单线程池
ScheduledExecutorService ThreadPool3 = Executors.newScheduledThreadPool(5);//定时功能的一个线程池
这种方式和Spring的一样,都可以直接调用execute()方法进行任务执行。或者可以自定义一个线程池。
ExecutorService ThreadPool4 = new ThreadPoolExecutor(5, 10, 3000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(),new ThreadPoolExecutor.CallerRunsPolicy());这里的参数都可以根据自己需要进行设置,具体的细节可以后面慢慢研究。要学的太多,加油加油