为什么在这种情况下ExecutorService返回正确答案19次?错误在哪里?

问题描述

这是代码。它刮了一个论坛帖子并显示结果。它应该只返回1个帖子,但返回19个帖子。线程参数是论坛的URL。第一页和第二页是要剪贴的范围。

@PostMapping("/search")
public String scrapPosts(@RequestParam(name = "thread",required = true) final String thread,@RequestParam(name = "firstPage",required = true)final int firstPage,@RequestParam(name = "secondPage",required = true)final int secondPage,Model model) throws IOException {
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    List<Post> postList = new ArrayList<>();

    for (int i = firstPage; i <secondPage; i++) {
        int finalI = i;
        Document doc = Jsoup.connect(thread + "page-" + finalI).get();
        Elements posts = doc.getElementsByClass("message-inner");
        posts.remove(posts.size() - 1);

        executorService.submit(()->{
                try {
                    for (int j = 0; j < posts.size(); j++) {
                        int finalJ = j;
                        postList.add(createNewPost(posts.get(finalI),thread,finalJ));
                    }

                } catch (Exception e) {
                    e.printstacktrace();
                }
            });
    }
    executorService.shutdown();


    try {
        executorService.awaitTermination(100000,TimeUnit.SECONDS);
        System.out.println("Srednia cena to \n");
        model.addAttribute("postList",postList);


    } catch (InterruptedException e) {
        System.out.println("Could not stop in alloted time");
    }

    executorService.shutdown();
    return "search";

}

返回的内容如下:

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)