---
title: "CountDownLatch(一个同步辅助类)"
author: "wisfly"
date: "2016-03-21T16:27:49Z"
tags: []
categories: ["行业应用"]
slug: "countdownlatch"
draft: false
lastmod: "2020-04-27T18:21:38Z"
id: 2285196
url: "https://wisfly.iteye.com/blog/2285196"
---

小伙伴们，我开了一家海淘护肤品淘宝店，搜索店铺“禾子蝶的海淘铺”，正品保证，欢迎进店选购哦。谢谢！

 

CountDownLatch，一个同步辅助类，在完成一组正在其他线程中执行的操作之前，它允许一个或多个线程一直等待。

主要方法

 public CountDownLatch(int count);

 public void **countDown**();

 public void **await**() throws [InterruptedException](http://www.iteye.com/java/lang/InterruptedException.html "java.lang 中的类")  
 

构造方法参数指定了计数的次数

countDown方法，当前线程调用此方法，则计数减一

awaint方法，调用此方法会一直阻塞当前线程，直到计时器的值为0,保证线程同步。

 

例如：

 Baiye片段代码：

public Appclient buildApp(final AppParam appDTO) throws Exception {  
        final Appclient client = new Appclient();  
        client.setAppid(appDTO.getAppid());  
        int count = appDTO.getPlatformAndriod() + appDTO.getPlatformIos();  
        final CountDownLatch countdown = new CountDownLatch(count);  
        if (appDTO.getPlatformAndriod() == 1) {  
            Thread androidThread = new Thread() {  
                public void run() {  
                    try {  
                        String releaseUrl = buildAndriod(appDTO, client);  
                        if (releaseUrl != null)  
                            client.setAndroidFile(releaseUrl);  
                        countdown.countDown();  
                        logger.info("Build android finished:" + releaseUrl);  
                    } catch (Exception e) {  
                        countdown.countDown();  
                        logger.error(e.getMessage(), e);  
                    }  
                }  
            };  
            androidThread.start();  
        }  
        if (appDTO.getPlatformIos() == 1) {  
            Thread iosThread = new Thread() {  
                public void run() {  
                    try {  
                        String releaseUrl = null;  
                        releaseUrl = buildIos(appDTO, client);  
                        if (releaseUrl != null)  
                            client.setIosFile(releaseUrl);  
                        countdown.countDown();  
                        logger.info("Build ios finished:" + releaseUrl);  
                    } catch (Exception e) {  
                        countdown.countDown();  
                        logger.error(e.getMessage(), e);  
                    }

                }  
            };  
            iosThread.start();  
        }  
        countdown.await();  
        return client;  
    }

 

 

public String buildAndriod(AppParam appDTO, Appclient client)  
            throws Exception {  
        // 1.Create build directory  
        String appBuildDir = Utility.APP\_PKG\_DIR + "/app" + appDTO.getAppid()  
                + "/android";  
        FileUtil.createDir(appBuildDir);  
        String andriodAppFileName = Cn2Spell.converterToSpell(appDTO.getName())  
                .replaceAll(" ", "\_").replaceAll("\_", "");  
        String andriodAppFile = "/app" + appDTO.getAppid() + "/android/"  
                + andriodAppFileName + "-release.apk";  
        String downloadUrlStr =andriodAppFile;  
        // 2.Create config.xml  
        Document document = DocumentHelper.createDocument(); // 创建文档  
        Element root = document.addElement("root");  
        Element appname = root.addElement("appname");  
        Element appid = root.addElement("appid");  
        Element apkname = root.addElement("appfilename");  
        Element packagename = root.addElement("packagename");  
        Element desc = root.addElement("description");  
        Element downloadUrl = root.addElement("downloadurl");  
        Element loadURL = root.addElement("loadURL");  
        Element p12password = root.addElement("p12password");// ios预留字段

        p12password.setText("test");  
        String package\_name = "by"  
                + Cn2Spell.converterToSpell(appDTO.getName())  
                        .replaceAll(" ", "").replaceAll("\_", "")  
                + Random.getRandomInt(4);  
        loadURL.setText(Config.getString("appH5Url")+appDTO.getUrl());  
        appname.setText(appDTO.getName());// 设置app 名字  
        appid.setText(appDTO.getAppid());// h5地址  
        apkname.setText(andriodAppFileName);// 设置应用名  
        packagename.setText(package\_name);// 设置包名  
        desc.setText("");//  
        downloadUrl.setText(downloadUrlStr);  
        // 设置Android相关配置  
        client.setApkName(Cn2Spell.converterToSpell(appDTO.getName()));  
        client.setPackageName(package\_name);

        XMLWriter xmlWriter = null;  
        // 生成配置文件  
        String configFile = appBuildDir + "/build\_config.xml";  
        try {  
            OutputFormat outFormat = OutputFormat.createPrettyPrint();  
            outFormat.setEncoding("UTF-8");  
            outFormat.setTrimText(false);  
            xmlWriter = new XMLWriter(new FileOutputStream(configFile),  
                    outFormat);  
            xmlWriter.write(document);  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }

        // 4.Copy img file from net  
        String apkImgDir = appBuildDir + "/png/";  
        FileUtil.createDir(apkImgDir);  
        String srcFile = Constant.PIC\_SERVER\_VPN + appDTO.getIcon();  
        String dstfile = apkImgDir + Utility.APP\_ANDRIOD\_ICON\_NAME;  
        ImgHelper.writeImg(srcFile, dstfile);

        // 4.Run build cmd  
        JavaShellUtil shellUtil = new JavaShellUtil();

        dstfile = appBuildDir + "/build\_android.sh";  
        FileUtil.copyFile(new File(Utility.SH\_DIR), new File(dstfile));

        String shellCmd = "sh " + appBuildDir + "/build\_android.sh "  
                + appBuildDir;  
        logger.info("sh command:" + shellCmd);  
        shellUtil.executeShell(shellCmd);

        FastdfsUtil fast = new FastdfsUtil();  
        String\[] rsPath = fast.uploadFile(appBuildDir + "/"  
                + andriodAppFileName + "-release.apk", "apk", null);  
        downloadUrlStr = "/" + rsPath\[0] + "/" + rsPath\[1];

        // 5.Check build status  
        logger.info("Android DownloadFile:" + Utility.APP\_PKG\_DIR  
                + andriodAppFile);  
        if (FileUtil.isFileExist(Utility.APP\_PKG\_DIR + andriodAppFile)) {  
            // appDTO.setAndriodAppFile(andriodAppFile);  
            return downloadUrlStr;  
        } else {  
            return null;  
        }  
    }

    /\**  
     * 生成IOS客户端  
     *  
     * @param appDTO  
     * @param client  
     * @return  
     * @throws Exception  
     \*/  
    public String buildIos(AppParam appDTO, Appclient client) throws Exception {  
        // 1.Create build directory  
        String appBuildDir = Utility.APP\_PKG\_DIR + "/app" + appDTO.getAppid()  
                + "/ios";  
        FileUtil.createDir(appBuildDir);  
        String iosAppFileName = Cn2Spell.converterToSpell(appDTO.getName())  
                .replaceAll(" ", "\_").replaceAll("\_", "");  
        String iosAppFile = "/app" + appDTO.getAppid() + "/ios/"  
                + iosAppFileName + "-release.ipa";  
        String downloadUrlStr =iosAppFile;  
        // 2.Create config.xml  
        Document document = DocumentHelper.createDocument(); // 创建文档  
        Element root = document.addElement("root");  
        Element appname = root.addElement("appname");  
        Element appid = root.addElement("appid");  
        Element apkname = root.addElement("appfilename");  
        Element packagename = root.addElement("packagename");  
        Element desc = root.addElement("description");  
        Element downloadUrl = root.addElement("downloadurl");  
        Element loadURL = root.addElement("loadURL");  
        Element p12password = root.addElement("p12password");// ios预留字段

        p12password.setText("123456");  
        String package\_name = "by"  
                + Cn2Spell.converterToSpell(appDTO.getName())  
                        .replaceAll(" ", "").replaceAll("\_", "")  
                + Random.getRandomInt(4);  
        loadURL.setText(Config.getString("appH5Url")+appDTO.getUrl());  
        appname.setText(appDTO.getName());// 设置app 名字  
        appid.setText(appDTO.getAppid());// h5地址  
        apkname.setText(iosAppFileName);// 设置应用名  
        packagename.setText(package\_name);// 设置包名  
        desc.setText("");//  
        downloadUrl.setText(downloadUrlStr);  
        // 设置IOS相关配置  
        client.setApkName(Cn2Spell.converterToSpell(appDTO.getName()));  
        client.setPackageName(package\_name);

        XMLWriter xmlWriter = null;  
        // 生成配置文件  
        String configFile = appBuildDir + "/build\_config.xml";  
        try {  
            OutputFormat outFormat = OutputFormat.createPrettyPrint();  
            outFormat.setEncoding("UTF-8");  
            outFormat.setTrimText(false);  
            xmlWriter = new XMLWriter(new FileOutputStream(configFile),  
                    outFormat);  
            xmlWriter.write(document);  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }

        // 4.Copy img file from net  
        String apkImgDir = appBuildDir + "/png/";  
        FileUtil.createDir(apkImgDir);  
        String srcFile = Constant.PIC\_SERVER\_VPN + appDTO.getIcon();  
        String dstfile = apkImgDir + Utility.APP\_IOS\_ICON\_NAME1;  
        String dstfile2 = apkImgDir + Utility.APP\_IOS\_ICON\_NAME2;  
        ImgHelper.writeImg(srcFile, dstfile);  
        ImgHelper.writeImg(srcFile, dstfile2);  
        // 4.Run build cmd  
        JavaShellUtil shellUtil = new JavaShellUtil();

        dstfile = appBuildDir + "/build\_ios.sh";  
        FileUtil.copyFile(new File(Utility.SH\_DIR\_IOS), new File(dstfile));

        String shellCmd = "sh " + appBuildDir + "/build\_ios.sh " + appBuildDir;  
        logger.info("sh command:" + shellCmd);  
        shellUtil.executeShell(shellCmd);

        FastdfsUtil fast = new FastdfsUtil();  
        String\[] rsPath = fast.uploadFile(appBuildDir + "/" + iosAppFileName  
                + "-release.ipa", "ipa", null);  
        String ipa= Config.getString("APP\_DOWNLOAD\_SERVER\_IOS")  
                + rsPath\[0] + "/" + rsPath\[1];  
        //生成plist文件  
        String\[] rsPathIcon = fast.uploadFile( apkImgDir + Utility.APP\_IOS\_ICON\_NAME1, "png", null);  
        String iconUrl= Config.getString("APP\_DOWNLOAD\_SERVER\_IOS")  
                + rsPathIcon\[0] + "/" + rsPathIcon\[1];  
        String iconUrl1=iconUrl+"?filename="+Utility.APP\_IOS\_ICON\_NAME1;  
        String iconUrl2=iconUrl+"?filename="+Utility.APP\_IOS\_ICON\_NAME2;  
        String plistContent=IosPlist.getPlist(ipa, iconUrl1,iconUrl2, package\_name, iosAppFileName);  
         
        String \[]plist=fast.uploadFile(plistContent.getBytes(), "plist", null);  
        downloadUrlStr="/"  
                + plist\[0] + "/" + plist\[1];  
        // 5.Check build status  
        logger.info("ios DownloadFile:" + Utility.APP\_PKG\_DIR + iosAppFile);  
        if (FileUtil.isFileExist(Utility.APP\_PKG\_DIR + iosAppFile)) {  
            return downloadUrlStr;  
        } else {  
            return null;  
        }  
    }

 

小伙伴们，我开了一家海淘护肤品淘宝店，搜索店铺“禾子蝶的海淘铺”，正品保证，欢迎进店选购哦。谢谢！