java多线程处理持续任务

package com.winterchen.service.thread;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.winterchen.dao.ThreadTaskDao;

@Service
public class ThreadTaskDemo {

    @Autowired
    ThreadTaskDao threadTaskDao;
    
    //最大线程数
    public static int maxThreadCount = 100;
    
    //线程池
    public ExecutorService executorService = Executors.newFixedThreadPool(ThreadTaskDemo.maxThreadCount);
    
    //处理的任务列表
    public static List<Map<String,Object>> curTaskList = new CopyOnWriteArrayList<Map<String,Object>>();
    
    
    /**
     * 任务处理
     */
    public void taskExec(){
        int execTotalCount = 0;
        try{
            while(true){
                
                //删除已处理完的对象
                for(Map<String,Object> curTaskMap : curTaskList){
                    if(curTaskMap.get("taskFlag").equals("1")){
                        curTaskList.remove(curTaskMap);
                        /* Iterator<Map<String,Object>> it_b= ThreadTaskDemo.curTaskList.iterator();
                          while(it_b.hasNext()){
                            Map<String,Object> a=it_b.next();
                            if (a.get("id").equals(map.get("id"))) {
                                it_b.remove();
                            }
                        }*/
                    }
                }
                
                System.out.println(execTotalCount++  + "——————————————————————————————开始任务,当前任务数: " + curTaskList.size() +"————————————————————————");
                
                List<Map<String,Object>> taskList = threadTaskDao.selectTasks();
                
                if(taskList.size() > 0){
                    
                    int addNewCount = 0;
                    
                    //添加新任务(需要去除正在执行的任务,避免重复处理)
                    for(Map<String,Object> newMap : taskList){
                        boolean isExists = false;    
                        
                        for(Map<String,Object> curTaskMap : curTaskList){
                            if(newMap.get("id").equals(curTaskMap.get("id"))){
                                isExists = true;
                                break;
                            }
                        }
                        
                        //新任务,处理
                        if(!isExists){
                            if(curTaskList.size() < ThreadTaskDemo.maxThreadCount){
                                addNewCount ++;
                                curTaskList.add(newMap);
                                executorService.execute(new RunnableThreadDemo1(newMap,threadTaskDao));
                            }
                        }
                    }
                    
                    System.out.println("——————————————————————————————新加"+ addNewCount +" 个任务,当前任务数:"+ curTaskList.size());
                    
                }
                //等待1秒执行
                Thread.sleep(1000);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
}


class RunnableThreadDemo1 implements Runnable{

    private Map<String,Object> map;
    private ThreadTaskDao threadTaskDao;
    
    public RunnableThreadDemo1(Map<String,Object> map,ThreadTaskDao threadTaskDao){
        this.map = map;
        this.threadTaskDao = threadTaskDao;
    }
    
    @Override
    public void run() {
        try {
            Long execTime = Long.valueOf((Integer) map.get("execTime")*100);
            System.out.println();
            System.out.println(map.get("taskCode") + " 等待时长:" + execTime/1000 + " 秒");
            Thread.sleep(execTime);
            threadTaskDao.udpateTaskById(String.valueOf(map.get("id")));
            //标识已完成
            map.put("taskFlag", "1");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}
 

<select id="selectTasks" resultType="map">
      SELECT id,task_code AS taskCode,task_name AS taskName,
        exec_time AS execTime,remark,task_flag AS taskFlag 
        FROM `t_thread_task`
        WHERE task_flag = '0'
        LIMIT 0,100
    </select>
    
     <update id="udpateTaskById" parameterType="string">
        <![CDATA[
            update `t_thread_task` set task_flag = '1',
            exec_num = exec_num +1
            where id =  #{id}
        ]]>
     </update>

Create Table

CREATE TABLE `t_thread_task` (
  `id` int NOT NULL AUTO_INCREMENT,
  `task_code` varchar(255) NOT NULL,
  `task_name` varchar(255) NOT NULL,
  `exec_time` int DEFAULT '0',
  `remark` varchar(200) DEFAULT NULL,
  `task_flag` varchar(1) NOT NULL DEFAULT '0',
  `exec_num` int NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值