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

来源:互联网 发布:win10装mac虚拟机 编辑:程序博客网 时间:2024/04/30 00:59

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

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: 检查卡信息所在数据表 */@Componentpublic 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

原创粉丝点击