需要一些线程建议

时间:2013-09-19 13:57:49

标签: android multithreading runnable

我有一个可以从网站下载图片的应用程序,

它完美运行,但只有一件事让我烦恼,它是CPU密集型的。

这是我的代码,任何人都可以提出任何建议如何处理这个?

非常感谢你!

Task.java

public class Task implements Runnable {

private String url;
private int server;

public Task(String url, int server) {
    this.url = url;
    this.server = server;
}

@Override
public void run() {
    android.os.Process
            .setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
    int page = 1;
    String r1 = "";
    if (server == 1) {
        r1 = getRaw(url);
    } else if (server == 2) {
        url = url + "page/";
        r1 = getRaw(url + page);
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String subs = url.substring(0, url.lastIndexOf('/') + 1);
    List<String> a1 = getPackage(r1, server);
    String t1 = getImageLink(r1, server);
    String loc = DownloadXML.UNDUH + File.separator + a1.get(0)
            + File.separator + a1.get(1) + ' ' + a1.get(2);
    File f1 = new File(loc);
    if (!f1.exists())
        f1.mkdirs();
    getImage(loc, t1, page);
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    page++;
    if (server == 1) {
        while (true) {
            r1 = getRaw(subs + page);
            t1 = getImageLink(r1, server);
            if (t1 != null) {
                getImage(loc, t1, page);
                page++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                break;
            }
        }
        return;
    } else if (server == 2) {
        int maxPage = Integer.parseInt(a1.get(3));
        while (page <= maxPage) {
            r1 = getRaw(subs + page);
            t1 = getImageLink(r1, server);
            if (t1 != null) {
                getImage(loc, t1, page);
                page++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                break;
            }
        }
        return;
    }

}

private String getRaw(String link) {
    String raw = null;
    try {
        URL myUrl = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
        conn.setRequestProperty(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
        InputStreamReader is = new InputStreamReader(conn.getInputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            raw += line;
        }
        is.close();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return raw;
}

private List<String> getPackage(String raw, int server) {
    List<String> pack = new ArrayList<String>();
    switch (server) {
    case 1:
        Pattern pattern = Pattern
                .compile("<span class=\"visible-desktop visible-tablet.+?</span>.+?<span class=\"visible-desktop visible-tablet.+?</span>");
        Matcher matcher = pattern.matcher(raw);
        String b = null;
        while (matcher.find()) {
            b = matcher.group();
            if (b != null) {
                String[] t = b.split("<[^>]*>");
                for (int i = 0; i < t.length; i++) {
                    if (!t[i].isEmpty()) {
                        pack.add(t[i].trim());
                    }
                }
            }
        }
        break;
    case 2:
        Pattern pattern1 = Pattern
                .compile("<div class=\"topbar_left\">.+?</a>.+?</a>");
        Matcher matcher1 = pattern1.matcher(raw);
        Pattern pPage = Pattern.compile("<div class=\"tbtitle dropdown_parent dropdown_right\"><div class=\"text\">[0-9]+ </div>");
        Matcher mPage = pPage.matcher(raw);
        while (matcher1.find()) {
            String s = matcher1.group().trim();
            s = s.replaceAll("<[^>]*>", "");
            String[] temp = s.split("[:]+");
            for (int i = 0; i < temp.length; i++) {
                if (temp[i] != null)
                    if (i == 1) {
                        pack.add(temp[i].replaceAll("[a-zA-z]+", "").trim());
                    } else if (i == 2) {
                        pack.add("- "
                                + temp[i].trim().replaceAll(
                                        "[^a-zA-z0-9]+", "_"));
                    } else {
                        pack.add(temp[i].trim());
                    }
            }
        }
        while (mPage.find()) {
            pack.add(mPage.group().replaceAll("<[^>]*>", "").trim());
        }
        break;
    }
    return pack;
}

private String getImageLink(String raws, int server) {
    /*
     * Return image link
     */
    switch (server) {
    case 1:
        Pattern pattern = Pattern.compile("http://img.+(jpg|png)");
        Matcher matcher = pattern.matcher(raws);
        while (matcher.find()) {
            return matcher.group();
        }
        break;
    case 2:
        Pattern pattern1 = Pattern
                .compile("http://manga.redhawkscans.com/content/comics/.+?(jpg|png)");
        Matcher matcher1 = pattern1.matcher(raws);
        while (matcher1.find()) {
            if (matcher1.group().contains("thumb")) {
                return null;
            } else {
                return matcher1.group();
            }
        }
        break;
    }
    return null;
}

private void getImage(String loc, String link, int page) {
    /*
     * Get image and save it
     */
    try {
        URL url = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
        String form = link.substring(link.lastIndexOf('.') + 1);
        String p = "0";
        if (page < 10) {
            p += Integer.toString(page);
        } else {
            p = Integer.toString(page);
        }
        File f = new File(loc, p + '.' + form);
        Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        FileOutputStream fos = new FileOutputStream(f);
        if (form == "jpg") {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } else {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        }
        conn.disconnect();
        fos.flush();
        fos.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
   }

在另一个类中,我只调用新的Thread(new Task(link,server))。start()来启动线程。

1 个答案:

答案 0 :(得分:0)

  1. 许多代码使用RegExps处理大字符串(网页?)

  2. 即时转换图像。

  3. 每次请求都有新的URLConnection。

  4. 尝试:

    1. 测试您的RegExp的性能并使用它。简短而复杂的RegExps如[abc]在大字符串上非常慢。

    2. 你真的需要重新压缩你的位图吗?将原始流存储到文件而不是重新压缩它可能更好吗?

    3. 创建连接池或共享连接以增加连接时间并最大限度地减少不需要的初始化。

    4. 您也可以尝试最小化后台的线程优先级: android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);