spring定时任务.线程池,自定义多线程配置

定时任务及多线程配置xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       "> 
    <!--  job start-->
    
    <!-- 定时 -->
    <bean id="ruleBean"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="ruleService" />
        <property name="targetMethod" value="updateRule" />
         
     </bean> 

    <bean id="rule" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="ruleBean" />
        <!-- 每天凌晨一点执行 -->
        <property name="cronExpression" value="0 0 1 * * ?"/>
    </bean>
    
    <!-- 定时 end -->
    
    <bean id="startQuertz" lazy-init="false" autowire="no"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
         <property name="jobDetails">
          <list>
            <ref bean="ruleBean" />
          </list>
        </property>

        <property name="triggers">
          <list>
             <ref bean="rule" />
          </list>
        </property>
        <!-- 启动时延期10秒开始任务 -->
        <property name="startupDelay" value="10" />
    </bean>
    
    <!--  job end-->
    
    <bean id="threadPoolTaskExecutor"
      class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
      <!-- 核心线程数,默认为1 -->
      <property name="corePoolSize" value="1" />

      <!-- 最大线程数,默认为Integer.MAX_VALUE -->
      <property name="maxPoolSize" value="10" />

      <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE
          <property name="queueCapacity" value="1000" /> -->

      <!-- 线程池维护线程所允许的空闲时间,默认为60s -->
      <property name="keepAliveSeconds" value="300" />

      <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
      <property name="rejectedExecutionHandler">
          <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
          <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
          <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
          <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
          <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
      </property>
    </bean>
   
    <bean id="contextUtil" class="com.mythopoet.util.ContextUtil"></bean>
</beans>

定时任务JAVA类

RuleService.java

@Service
public class RuleService {
    public void updateRule(){
    
      System.out.println("定时任务启动");
    
    }

}

多线程配置

StartTaskThread.java

public class StartTaskThread implements Runnable {
     private List<String> list;
    

    public StartTaskThread(List<String> list) {
       this.list= list;
    }
    @Override
    public synchronized void run() {
           System.out.println(list.size());
    }
}

修改定时任务类,分配数据,并发布到各个线程里。

RuleService.java

@Service
public class RuleService {

    public void updateRule(){
        int nums = 5;//开启5线程
        List<String> strList= new ArrayList<String>();
        for (int i = 0; i < 2000; i++) {
            strList.add("test"+i);
        }
        Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
        for (int i = 0; i < nums; i++) {
            List<String> list = new ArrayList<String>();
            map.put(i, list);
        }
        int st = 0; //起点
        int avg = strList.size()/nums; //平均值
        int count =0;//记录值
        
        for (int i = 0; i < nums; i++) {
            if(i==nums-1){
                for (int j = count; j <strList.size(); j++) {
                    map.get(i).add(strList.get(j));
                    count++;
                }
                new Thread(new StartTaskThread(map.get(i)).start();
break; } for (int j = st; j <(st+avg); j++) { map.get(i).add(strList.get(j)); count++; } st=st+avg;
            new Thread(new StartTaskThread(map.get(i)).start();
 } }

取线程配置工具类,如果线程内需要操作DAO 则需要主动获取spring注入的DAO类的Bean

ContextUtil.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ContextUtil implements ApplicationContextAware{

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext(){
        return context;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

}

获取dao写法

RuleDAO ruleDAO =(RuleDAO) ContextUtil.getBean("ruleDAO");
                

 

 

使用线程池

StartTaskThread2.java

public class StartTaskThread implements Runnable {
     private String st;
    

    public StartTaskThread(String st) {
       this.st= st;
    }
    @Override
    public void run() {
           System.out.println(st);
    }
}

线程池

RuleService2.java

@Service
public class RuleService {

    public void updateRule(){

ThreadPoolTaskExecutor tpte =(ThreadPoolTaskExecutor)ContextUtil.getBean("threadPoolTaskExecutor");
        List<String> strList= new ArrayList<String>();
        for (int i = 0; i < 2000; i++) {
            strList.add("test"+i);
        }

        for (int i = 0; i < strList.size(); i++) {
            tpte.execute(new StartTaskThread2(strList.get(i)));
        }
}

 

posted @ 2016-06-23 18:13  茫洋  阅读(29410)  评论(0编辑  收藏  举报