微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么在这种情况下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 举报,一经查实,本站将立刻删除。