spring线程池,全部执行完子线程在执行主线程

第一步:
spring进行线程池的配置
<bean id="newDis"
     class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
   <property name="corePoolSize" value="5" />  
   <property name="keepAliveSeconds" value="300" />    
   <property name="maxPoolSize" value="500" />     
   <property name="queueCapacity" value="50" />   
   <property name="rejectedExecutionHandler">
      <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
   property>
bean>

第二步:
获取newDis这个bean开启线程
//countDownLatch是jdk自带的封装的同步方法,参数为开启线程的数量大小
 
  
final CountDownLatch countDownLatch=new CountDownLatch(lists.size());

 
  
 
  
for(final List list:lists){

   //开启线程
   threadPoolTaskExecutor = ApplicationContextUtil.getBean("newDis", ThreadPoolTaskExecutor.class);
   threadPoolTaskExecutor.execute(new Runnable() {
      //解决多线程操作同一集合
      @Override
      public void run() {
         System.out.println("--子线程--");
         try {
		//模拟业务代码
        	Thread.sleep(2000);
         }catch (Exception e){
            

         }finally {
		
            countDownLatch.countDown();//工人完成工作,计数器减一
         }
      }
   });
}
 
  
 
  
try {
  //等待子线程全部结束
   countDownLatch.await();
   
} catch (Exception e) {
   e.printStackTrace();
}
 
  
System.out.println("-------------主线程执行---------------");



你可能感兴趣的:(spring线程池,全部执行完子线程在执行主线程)