线程化递归函数

时间:2015-10-29 20:44:49

标签: java multithreading recursion

我有这个递归函数,可以在URL上找到hrefs并将它们全部添加到全局列表中。这是同步完成的,需要很长时间。我曾尝试使用线程进行此操作,但未能将所有线程写入一个列表。有人可以告诉我如何使用线程进行此操作吗?

private static void buildList (String BaseURL, String base){
    try{
        Document doc = Jsoup.connect(BaseURL).get();
        org.jsoup.select.Elements links = doc.select("a");
        for(Element e: links){
            //only if this website has no longer been visited
            if(!urls.contains(e.attr("abs:href"))){
                //eliminates pictures and pdfs
                if(!e.attr("abs:href").contains(".jpg")){
                    if(!e.attr("abs:href").contains("#")){
                        if(!e.attr("abs:href").contains(".pdf")){
                            //makes sure it doesn't leave the website
                            if(e.attr("abs:href").contains(base)){
                                urls.add(e.attr("abs:href"));
                                System.out.println(e.attr("abs:href"));

                                //recursive call
                                buildList(e.attr("abs:href"),base);
                            }
                        }
                    }
                }
            }
        }
    } catch(IOException ex) {

    }

    //to print out all urls.

    /*      
     * for(int i=0;i<urls.size();i++){
     * System.out.println(urls.get(i));
     * }
     */
}

2 个答案:

答案 0 :(得分:0)

这是ForkJoin的一个很好的用例。它将通过非常简单的代码提供优秀的并发性。

对于解析的网址集,请使用Collections.synchronizedSet(new HashSet<String>());

您还可以创建比您拥有的核心数量更大的ForkJoinPool,因为涉及到网络(常见用法期望每个线程将以~100%的速度执行工作)。

答案 1 :(得分:0)

使用并发包中的任何集合来存储从不同线程获得的值。 ArrayBloac

一旦你将问题分解为分裂并征服算法,你就可以使用fork和join。