多线程Future+Callable实现并发查询

对于所查询的数据比较耗时,数据位于不同的数据源中,可以通过并发查询的方式加快获取想要的数据。记录项目中用到的方法。

package com.lancy.interfaces.util;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.lancy.interfaces.lnt.service.LntCardService;
import com.lancy.interfaces.ykt.service.YktCardService;

/**
 * @ClassName: CardUtil.java
 * @Description: 检查卡信息所在数据表
 */
@Component
public class CardUtil {
    private static YktCardService yktCardService;
    private static LntCardService lntCardService;
    private static ExecutorService threadPool = null;

    static {
        threadPool = Executors.newFixedThreadPool(200);
    }

    @Resource
    public void setYktCardService(YktCardService service){
        yktCardService = service;
    }
    @Resource
    public void setLntCardService(LntCardService service){
        lntCardService = service;
    }

    /**
     * 判断卡类型
     * @param cardId 卡号
     * @return 1:储值卡,2:记账卡
     */
    public static int checkCardType(String cardId) {
        //用线程并发查询
        Future<Integer> lntCaball = threadPool.submit(new LntCardThread(cardId));
        Future<Integer> yktCaball = threadPool.submit(new YktCardThread(cardId));
        Integer result = null;
        try {
            result = lntCaball.get();
            if (result != null) {
                return result;
            }
        } catch (Exception e) {
            lntCaball.cancel(true);
        }

        try {
            result = yktCaball.get();
        } catch (Exception e) {
            yktCaball.cancel(true);
        }
        if (result == null)
            return -1;
        return result;
    }

    //实现Callable接口的线程类1,call方法执行业务逻辑
    private static class LntCardThread implements Callable<Integer> {
        private String cardId;
        public LntCardThead(String cardId) {
            this.cardId= cardId;
        }
        public Integer call() throws Exception {
            return lntCardService.getCardType(this.cardId);
        }
    }
    //实现Callable接口的线程类2,call方法执行业务逻辑
    private static class YktCardThread implements Callable<Integer> {
        private String cardId;
        public YktCardThead(String cardId) {
            this.cardId= cardId;
        }
        public Integer call() throws Exception {
            return yktCardService.getCardType(cardId);
        }
    }
}

对Future 和 Callable的介绍,可以查看此博主的文章,里面有详细介绍 http://blog.csdn.net/ghsau/article/details/7451464

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值