并发编程Executors的具体使用实例 springboot+newFixedThreadPool

@Service("updateRobotAmountService")
public class updateRobotAmountService {
private Logger logger = Logger.getLogger(updateRobotAmountService.class);
@Resource(name = "daoSupport")
private DaoSupport dao;

@Resource(name = "daoSupport2")
private DaoSupport2 dao2;

private ExecutorService executeService = null;

@PostConstruct
    public void initThreadPool()

    {

    //程序启动时初始化20个线程池大小的固定线程池

        executeService = Executors.newFixedThreadPool(20);
    }

/**
* 摧毁线程池
*/
    @PreDestroy
    public void shutdownThreadPool()
    {
        executeService.shutdown();
    }


public void work()  {

try {

                    //查询数据

List list=(List) dao2.findForList("AccountMapper.getRobot", null);

if(list!=null&&list.size()>0){

                //实例化一个无界队列

LinkedBlockingQueue batchQueue = new LinkedBlockingQueue();

for(int i=0;i

                //将数据放在队列里

PageData data1=list.get(i);
batchQueue.put(data1);
}

for(int i=0;i

                  //启动线程从对列里面取出数据执行

Task tasks = new Task(batchQueue);
  executeService.execute(tasks);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.toString());
}
}


private class Task implements Runnable{


private LinkedBlockingQueue BatchQueue;
 
 
public Task(LinkedBlockingQueue bQueue){
    this.BatchQueue=bQueue;
    }

@Override
public void run() {

try {

                            //从队列里面拿出一个数据执行

PageData p1 = BatchQueue.take();

List pList=(List) dao2.findForList("AccountMapper.getRobotAmount", p1);

List robot_list=(List) dao2.findForList("AccountMapper.getRobotList", p1);

for(int j=0;j PageData p=robot_list.get(j);
dao.update("AccountMapper.updateAmountForSteamUid",p);

int app_id=(int) p.get("app_id");

Optional countDataOptional=pList.stream().filter(d->(int)d.get("app_id")==app_id).findFirst();

if(countDataOptional.isPresent()){
PageData countData=countDataOptional.get();
p.put("amount", countData.get("amount"));
int code=(int) dao.update("AccountMapper.updateAmount", p);
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}
}

你可能感兴趣的:(并发,Executors)