Java 9多线程HTTP请求

Java 9多线程HTTP请求,java,multithreading,concurrency,java-9,http2,Java,Multithreading,Concurrency,Java 9,Http2,我不知道如何将下面的顺序代码正确地转换为多线程。我已经尽了最大努力避免任何共享资源和完全的线程独立性 这是单线程代码 com.net软件包 import jdk.incubator.http.HttpClient; import jdk.incubator.http.HttpRequest; import jdk.incubator.http.HttpResponse; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; impor

我不知道如何将下面的顺序代码正确地转换为多线程。我已经尽了最大努力避免任何共享资源和完全的线程独立性

这是单线程代码 com.net软件包

import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class ReqSingle {

    private float totalElapsedTime = 0F;
    private HttpClient client = HttpClient.newHttpClient();

    public ReqSingle(String[] sties){
        for (String site : sties){
            long fetchStartTime = System.currentTimeMillis();
            String html = getResource(site);
            float elapsed = (float) (System.currentTimeMillis() - fetchStartTime) / 1000;

            Document doc = Jsoup.parse(html);
            System.out.println("It took " + elapsed + " seconds to fetch " + site + " with title " + doc.title());
            totalElapsedTime += elapsed;
        }

        System.out.println("Total Elapsed Time: " + totalElapsedTime + "\nTotal Number of sites: " + sties.length);
    }

    private String getResource(String someUrl) {
        String body = "";
        try {
            URI url = new URI(someUrl);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(url).GET().build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
            body = response.body();
        } catch (URISyntaxException e) {
            System.out.println("URL " + someUrl + "is not valid");
        } catch (IOException | InterruptedException e) {
            // do nothing
        }
        return body;
    }
}
输出:

WARNING: Using incubator modules: jdk.incubator.httpclient
Single Threaded Test Results:

It took 2.843 seconds to fetch https://www.aparat.com/ with title آپارات - سرویس اشتراک ویدیو
It took 0.459 seconds to fetch http://www.varzesh3.com/ with title 
It took 0.52 seconds to fetch http://namnak.com/ with title نمناک
It took 2.231 seconds to fetch http://www.telewebion.com/ with title تلوبیون | مرجع پخش زنده و دانلود فیلم ، سریال و سایر برنامه های تلویزیون
It took 0.243 seconds to fetch https://divar.ir/ with title 
It took 1.749 seconds to fetch https://www.ninisite.com/ with title نی نی سایت | راهنمای بارداری و بچه داری
It took 0.407 seconds to fetch https://www.blogfa.com/ with title 
It took 1.796 seconds to fetch http://www.namasha.com/ with title نماشا - سرویس رایگان اشتراک ویدیو
It took 0.232 seconds to fetch http://www.yjc.ir/ with title 
Total Elapsed Time: 10.48
Total Number of sites: 9


Multi Threaded Test Results:

It took 0.114 seconds to fetch https://divar.ir/ with title 
It took 0.236 seconds to fetch http://www.yjc.ir/ with title 
It took 1.519 seconds to fetch http://www.varzesh3.com/ with title 
It took 1.587 seconds to fetch https://www.blogfa.com/ with title 
It took 3.524 seconds to fetch http://namnak.com/ with title نمناک
It took 4.152 seconds to fetch https://www.ninisite.com/ with title نی نی سایت | راهنمای بارداری و بچه داری
It took 4.486 seconds to fetch http://www.namasha.com/ with title نماشا - سرویس رایگان اشتراک ویدیو
It took 4.725 seconds to fetch https://www.aparat.com/ with title آپارات - سرویس اشتراک ویدیو
It took 5.82 seconds to fetch http://www.telewebion.com/ with title تلوبیون | مرجع پخش زنده و دانلود فیلم ، سریال و سایر برنامه های تلویزیون

你的代码是正确的。但建议使用一些实现来控制线程数

e、 g:


即使有大量的rawuri。它将持续点击线程数。

在您的示例中,没有理由自己创建线程;你可以简单地利用它。根据其文件:

使用此客户端和给定的响应处理程序异步发送给定的请求


此外,您应该使用JMH来正确地对Java程序进行基准测试。请参阅:

为什么不直接使用
执行器服务
?这将使多线程部分简单得多。另外,您的多线程代码有什么问题?我看不到任何错误。你期望发生什么事情而不是?@Kayman为什么不找出这段代码的问题所在。我现在正处于学习阶段。@markspace谢谢你的时间。因此,代码是正确的,我将对代码和其他答案进行更多的实验,以更好地了解问题。虽然代码已经很好,但许多用户建议使用ExecutorService,因此我认为这可能是答案
package com.net;

public class ReqTester {
    public static void main(String[] args) {

        String[] topIranianSites = {
                "https://www.aparat.com/",
                "http://www.varzesh3.com/",
                "http://namnak.com/",
                "http://www.telewebion.com/",
                "https://divar.ir/",
                "https://www.ninisite.com/",
                "https://www.blogfa.com/",
                "http://www.namasha.com/",
                "http://www.yjc.ir/"
        };

        System.out.println("Single Threaded Test Results:\n");
        new ReqSingle(topIranianSites);
        System.out.println("\n\nMulti Threaded Test Results:\n");
        new ReqThreaded(topIranianSites);

    }
}
WARNING: Using incubator modules: jdk.incubator.httpclient
Single Threaded Test Results:

It took 2.843 seconds to fetch https://www.aparat.com/ with title آپارات - سرویس اشتراک ویدیو
It took 0.459 seconds to fetch http://www.varzesh3.com/ with title 
It took 0.52 seconds to fetch http://namnak.com/ with title نمناک
It took 2.231 seconds to fetch http://www.telewebion.com/ with title تلوبیون | مرجع پخش زنده و دانلود فیلم ، سریال و سایر برنامه های تلویزیون
It took 0.243 seconds to fetch https://divar.ir/ with title 
It took 1.749 seconds to fetch https://www.ninisite.com/ with title نی نی سایت | راهنمای بارداری و بچه داری
It took 0.407 seconds to fetch https://www.blogfa.com/ with title 
It took 1.796 seconds to fetch http://www.namasha.com/ with title نماشا - سرویس رایگان اشتراک ویدیو
It took 0.232 seconds to fetch http://www.yjc.ir/ with title 
Total Elapsed Time: 10.48
Total Number of sites: 9


Multi Threaded Test Results:

It took 0.114 seconds to fetch https://divar.ir/ with title 
It took 0.236 seconds to fetch http://www.yjc.ir/ with title 
It took 1.519 seconds to fetch http://www.varzesh3.com/ with title 
It took 1.587 seconds to fetch https://www.blogfa.com/ with title 
It took 3.524 seconds to fetch http://namnak.com/ with title نمناک
It took 4.152 seconds to fetch https://www.ninisite.com/ with title نی نی سایت | راهنمای بارداری و بچه داری
It took 4.486 seconds to fetch http://www.namasha.com/ with title نماشا - سرویس رایگان اشتراک ویدیو
It took 4.725 seconds to fetch https://www.aparat.com/ with title آپارات - سرویس اشتراک ویدیو
It took 5.82 seconds to fetch http://www.telewebion.com/ with title تلوبیون | مرجع پخش زنده و دانلود فیلم ، سریال و سایر برنامه های تلویزیون
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
executor.submit(new Site(rawUri));