java多线程并发程序执行慢有什么原因?该怎么解决?

我们在执行java多线程并发程序时有时候会碰到执行特别慢的场景,小伙伴们知道是什么原因导致的吗?它要怎么解决呢?下面小编就为你讲讲。

前提:在某地需要开发一个应用系统,此系统主要功能是能够让一些中小型企业填写企业资质信息,然后通过给定的公式,统计这一系列的信息,再以得分的形式展示给上头。当前总共有着1300家企业填报。因为得分是需要实时显示的,因此统计功能会慢到一定程度。

具体代码流程:

a.首先查出1300企业信息

b.循环遍历1300家企业的所有信息,并计算每家企业的具体得分。每家预计时间为0.3秒。合计390秒。所以页面请求超时

c.导出(jxl或jar)

给出解决方案:

因为是处理业务的,所以我们需要能有返回值的线程。因此会使用:Callable

实现

1、调用线程代码

List < Map < String, Object >> list = (List < Map < String, Object >> ) map.get("rows");
int taskSize = 20;
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务 
List < Future > listFuture = new ArrayList < Future > ();
for (int i = 0; i < taskSize; i++)
{
    System.out.println("我启用多线程啦啦啦");
    int evgCount = list.size() / taskSize;
    Callable c = new MyCallable(list.subList(evgCount * i, evgCount * (i + 1)), session, staticFlag
        , declareService, declareMasterService, enterpriseQueryService);
    // 执行任务并获取Future对象
    Future f = pool.submit(c);
    listFuture.add(f);
}
pool.shutdown();
// 获取所有并发任务的运行结果 
List < Map < String, Object >> listResult = new ArrayList < Map < String, Object >> ();
for (Future f: listFuture)
{
    List < Map < String, Object >> listModel = new ArrayList < Map < String, Object >> ();
    try
    {
        listModel = (List < Map < String, Object >> ) f.get();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
    catch (ExecutionException e)
    {
        e.printStackTrace();
    }
    listResult.addAll(listModel);
}
map.put("rows", listResult);

2、线程代码

package usi.jszx.controller;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import usi.jszx.entity.ScoreMain;
import usi.jszx.service.DeclareMasterService;
import usi.jszx.service.DeclareService;
import usi.jszx.service.EnterpriseQueryService;
import usi.sys.dto.AuthInfo;
import usi.sys.util.ConstantUtil;
class MyCallable implements Callable < Object >
{
    //-----------------以下为线程调用的方法----------------
    private List < Map < String
    , Object >> list;
    private HttpSession session;
    private String staticFlag;
    private DeclareService declareService;
    private DeclareMasterService declareMasterService;
    private EnterpriseQueryService enterpriseQueryService;
    public MyCallable(List < Map < String, Object >> list, HttpSession session, String staticFlag
        , DeclareService declareService, DeclareMasterService declareMasterService, EnterpriseQueryService enterpriseQueryService)
    {
        this.list = list;
        this.session = session;
        this.staticFlag = staticFlag;
        this.declareService = declareService;
        this.declareMasterService = declareMasterService;
        this.enterpriseQueryService = enterpriseQueryService;
    }
    @Override
    public Object call() throws Exception
    {
        AuthInfo info = (AuthInfo) session.getAttribute(ConstantUtil.AUTH_INFO);
        for (int i = 0; i < list.size(); i++)
        {
            Map < String, Object > maplist = list.get(i);
            String mainId = maplist.get("ID") + "";
            this.gradeMaster(session, mainId, maplist.get("orgId") + "", declareMasterService, enterpriseQueryService);
            List < Map < String, Object >> listscore = declareMasterService.queryScoreMain(maplist.get("ID") + "", info.getRightType(), "report");
            // declareMasterService.queryScoreMain(mainId,info.getRightType(),isreport);
            int isdouble = 1;
            if (listscore.size() > 30)
            {
                maplist.put("SOCRETOTAL", listscore.get(46)
                    .get("SCORE"));
                isdouble = 2;
            }
            else if (listscore.size() > 22)
            {
                maplist.put("SOCRETOTAL", listscore.get(23)
                    .get("SCORE"));
            }
            if ("3".equals(staticFlag))
            {
                for (int j = 0; j < 23; j++)
                {
                    if (j < 9)
                    {
                        maplist.put("VALUE0" + (j + 1), listscore.get(j * isdouble)
                            .get("SHOW_VALUE"));
                    }
                    else
                    {
                        maplist.put("VALUE" + (j + 1), listscore.get(j * isdouble)
                            .get("SHOW_VALUE"));
                    }
                }
            }
            //地市展示
            String COUNTYID = maplist.get("COUNTYID") + "";
            if ("340826".equals(COUNTYID) || "341822".equals(COUNTYID))
            {
                maplist.put("CITYNAME", maplist.get("COUNTYNAME") + "");
            }
            //企业类型
            String DECLARE_EVALUATE = maplist.get("DECLARE_EVALUATE") + "";
            if ("1".equals(DECLARE_EVALUATE))
            {
                maplist.put("DECLARE_EVALUATE_NAME", "申报");
            }
            else
            {
                maplist.put("DECLARE_EVALUATE_NAME", "评价");
            }
            //审核状态
            String SHSTATUS = maplist.get("SHSTATUS") + "";
            if ("9".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "草稿");
            }
            else if ("0".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "企业提交");
            }
            else if ("1".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "市审核通过");
            }
            else if ("2".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "市审核不通过");
            }
            else if ("3".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "省审核通过");
            }
            else if ("4".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "省审核不通过");
            }
            else if ("5".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "省级审核中");
            }
            else if ("6".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "退回企业修改");
            }
            else if ("7".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "市级审核中");
            }
            else if ("11".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "修改为申报");
            }
            else if ("12".equals(SHSTATUS))
            {
                maplist.put("STRSHSTATUS", "修改为评价");
            }
            if ("1".equals(staticFlag))
            {
                //添加修改意见
                List < Map < String, Object >> listDetail = declareService.queryAuditLog(mainId);
                if (listDetail.size() > 0)
                {
                    String AUDIT_OPINION = listDetail.get(0)
                        .get("AUDIT_OPINION") + "";
                    if (!StringUtils.isEmpty(AUDIT_OPINION) && !"null".equals(AUDIT_OPINION))
                    {
                        maplist.put("AUDIT_OPINION", AUDIT_OPINION);
                    }
                    else
                    {
                        maplist.put("AUDIT_OPINION", "");
                    }
                }
                //是否更名 曾用名
                String ORGNAME = maplist.get("ORGNAME") + "";
                String PJNAME = maplist.get("PJNAME") + "";
                if (StringUtils.isEmpty(PJNAME) || "null".equals(PJNAME) ||
                    PJNAME.equals(ORGNAME))
                {
                    maplist.put("ISGENGMING", "否");
                    maplist.put("PJNAME_E", "");
                }
                else
                {
                    maplist.put("ISGENGMING", "是");
                    maplist.put("PJNAME_E", PJNAME);
                }
            }
            else if ("2".equals(staticFlag))
            {}
        }
        return list;
    }
    public float gradeMaster(HttpSession session, String mainId, String orgId
        , DeclareMasterService declareMasterService, EnterpriseQueryService enterpriseQueryService)
    {
        AuthInfo info = (AuthInfo) session.getAttribute(ConstantUtil.AUTH_INFO);
        String rightType = info.getRightType();
        declareMasterService.deleteScoreMain(mainId);
        float[] resultFirst = new float[100];
        /*
         * 先查询所有 附表列表
         * 查看得分的地方,是直接查找主表数据的
         * 
         * 既然审核了,主表数据肯定存起来了
         * */
        List < Map < String, Object >> listDetail = declareMasterService.queryTaskDetail(mainId);
        if ("2".equals(rightType) || "3".equals(rightType))
        {
            //将String 转为 float
            for (int i = 0; i < listDetail.size(); i++)
            {
                Map < String, Object > map = listDetail.get(i);
                if (StringUtils.isEmpty(map.get("DECLARE_CITY_VALUE") + "") ||
                    "null".equals(map.get("DECLARE_CITY_VALUE") + ""))
                {
                    resultFirst[i] = 0 f;
                }
                else
                {
                    resultFirst[i] = float.parsefloat(map.get("DECLARE_CITY_VALUE") + "");
                }
            }
        }
        else
        {
            //将String 转为 float
            for (int i = 0; i < listDetail.size(); i++)
            {
                Map < String, Object > map = listDetail.get(i);
                if (StringUtils.isEmpty(map.get("DECLARE_PROVINCE_VALUE") + "") ||
                    "null".equals(map.get("DECLARE_PROVINCE_VALUE") + ""))
                {
                    resultFirst[i] = 0 f;
                }
                else
                {
                    resultFirst[i] = float.parsefloat(map.get("DECLARE_PROVINCE_VALUE") + "");
                }
            }
        }
        Map < String, Object > enterprise = enterpriseQueryService.getInfoByOrgId(orgId)
            .get(0);
        //根据 湖南省企业技术中心评价指标计算公式 进行算值 下一步算分
        float ratio1 = 0 f;
        float ratio2 = 0 f;
        float ratio3 = 0 f;
        try
        {
            ratio1 = float.parsefloat(enterprise.get("RATIO1") + "");
            ratio2 = float.parsefloat(enterprise.get("RATIO2") + "");
            ratio3 = float.parsefloat(enterprise.get("RATIO3") + "");
        }
        catch (Exception e)
        {}
        Map < String, Object > map = DeclareController.getValue(resultFirst, ratio1, ratio2, ratio3);
        float[] resultValue = (float[]) map.get("resultValue");
        float[] resultScoreValue = (float[]) map.get("resultScoreValue");
        float[] resultScore = DeclareController.getScore(resultScoreValue);
        float scoreTotal = 0 f;
        List < Map < String, Object >> listScore = declareMasterService.queryScoreDic();
        for (int i = 0; i < listScore.size(); i++)
        {
            ScoreMain scoreMain = new ScoreMain();
            scoreMain.setMainId(mainId);
            scoreMain.setScoreName(listScore.get(i)
                .get("SCORE_NAME") + "");
            scoreMain.setScoreUnit(listScore.get(i)
                .get("SCORE_UNIT") + "");
            scoreMain.setScoreWeight(listScore.get(i)
                .get("SCORE_WEIGHT") + "");
            scoreMain.setDisOrder(listScore.get(i)
                .get("DIS_ORDER") + "");
            scoreMain.setShowValue(resultValue[i] + "");
            scoreMain.setScoreValue(resultScoreValue[i] + "");
            scoreMain.setScore(resultScore[i] + "");
            declareMasterService.inserScoreMain(scoreMain);
            scoreTotal += resultScore[i];
        }
        return scoreTotal;
    }
}

PS:可以看到最后从390秒提速致40秒,提升巨大

以上就是整篇文章的所有内容,相信对多线程大家都已经非常了解了吧,还想了解更多相关java常见问题及解决方法的话就快关注我们网站吧。

推荐阅读:

java多线程实战,java多线程经典案例

java多线程实例,java线程之间如何通信?

java多线程,java多线程编程实例分享