CompletableFuture,主要永不退出 [英] CompletableFuture, main never exits

查看:371
本文介绍了CompletableFuture,主要永不退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java 8,以及"CompletableFuture"的详细信息. 跟随这个有趣的教程: https://www.callicoder.com/java-8-completablefuture-tutorial/

I'm learning Java 8 and more in detail the "CompletableFuture". Following this interesting tutorial: https://www.callicoder.com/java-8-completablefuture-tutorial/

我编写了以下Java类:

I wrote the following Java class :

package parallels;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;




public class Test {
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
    private static final Executor executor = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {

        List<String> webPageLinks= new ArrayList<String>();
        for (int i=0;i<30;i++) {
            webPageLinks.add("http://jsonplaceholder.typicode.com/todos/1");
        }

        // Download contents of all the web pages asynchronously
        List<CompletableFuture<String>> pageContentFutures = webPageLinks.stream()
                .map(webPageLink -> downloadWebPage(webPageLink))
                .collect(Collectors.toList());


        // Create a combined Future using allOf()
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                pageContentFutures.toArray(new CompletableFuture[pageContentFutures.size()])
                );


        // When all the Futures are completed, call `future.join()` to get their results and collect the results in a list -
        CompletableFuture<List<String>> allPageContentsFuture = allFutures.thenApply(v -> {
            return pageContentFutures.stream()
                    .map(pageContentFuture -> pageContentFuture.join())
                    .collect(Collectors.toList());
        });


    }



    private static CompletableFuture<String> downloadWebPage(String pageLink) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> getRequest(pageLink),executor);
        return completableFuture;
    } 

    public static String getRequest(String url) {
        System.out.println("getRequest");
        String resp =null;
        try {
            ResteasyClient client = new ResteasyClientBuilder().build();
            ResteasyWebTarget target = client.target(url);
            target.register((ClientRequestFilter) requestContext -> {
                requestContext.getHeaders().add("User-Agent",USER_AGENT);
            });
            Response response = target.request().get();
            resp= response.readEntity(String.class);
            System.out.println(resp);
            response.close();  
            client.close();

            System.out.println("End getRequest");
        }catch(Throwable t) {
            t.printStackTrace();
        }




        return resp;

    }



}

(要运行该代码,您需要"resteasy-client"库)

但是我不明白为什么即使收集了所有响应后main方法也不会终止...

But I don't understand why even when all the responses are collected the main method doesn't terminate...

我错过了什么吗? 有什么完整"方法可以在任何地方调用,如果可以的话,可以在哪里调用?

Did I miss something? Is there some "complete" method to call anywhere, and if yes where?

推荐答案

您的主要方法已完成,但是当您创建了其他仍处于活动状态的线程时,程序将继续运行.最好的解决方案是调用关闭.

Your main method completes, but the program continues running as you have created other threads which are still alive. The best solution is to call shutdown on your ExecutorService once you've submitted all your tasks to it.

或者,您可以创建一个使用daemon线程的ExecutorService(请参见

Alternatively you could create an ExecutorService which uses daemon threads (see the Thread documentation), or a ThreadPoolExecutor with allowCoreThreadTimeout(true), or just call System.exit at the end of your main method.

这篇关于CompletableFuture,主要永不退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆