1. 程式人生 > >spring定時任務.線程池,自定義多線程配置

spring定時任務.線程池,自定義多線程配置

sys wire eight void port itl edm 代碼 .org

定時任務及多線程配置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)));
        }
}
技術分享圖片

spring定時任務.線程池,自定義多線程配置