Concurrency 如何在java中并行执行多个sql查询

Concurrency 如何在java中并行执行多个sql查询,concurrency,parallel-processing,java-8,Concurrency,Parallel Processing,Java 8,我有3个方法,返回一个结果列表,我的sql查询在每个方法中执行,并返回一个结果列表。我想并行执行所有3个方法,这样它就不会等待一个和另一个方法的完成。我看到一个流动岗位,但它不工作。 这个链接是[ [ 我想用Java8特性来解决这个问题。 但是上面的链接如何调用多个方法请告诉我。适用于您的任务。下面是一个示例代码,演示了它: public static void main(String[] args) { // Create Stream of tasks: Stream<

我有3个方法,返回一个结果列表,我的sql查询在每个方法中执行,并返回一个结果列表。我想并行执行所有3个方法,这样它就不会等待一个和另一个方法的完成。我看到一个流动岗位,但它不工作。 这个链接是[ [

我想用Java8特性来解决这个问题。 但是上面的链接如何调用多个方法请告诉我。

适用于您的任务。下面是一个示例代码,演示了它:

public static void main(String[] args) {
    // Create Stream of tasks:
    Stream<Supplier<List<String>>> tasks = Stream.of(
            () -> getServerListFromDB(),
            () -> getAppListFromDB(),
            () -> getUserFromDB());

    List<List<String>> lists = tasks
            // Supply all the tasks for execution and collect CompletableFutures
            .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
            // Join all the CompletableFutures to gather the results
            .stream()
            .map(CompletableFuture::join).collect(Collectors.toList());
    System.out.println(lists);
}

private static List<String> getUserFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName() + " getUser");
    return Arrays.asList("User1", "User2", "User3");
}

private static List<String> getAppListFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName() + " getAppList");
    return Arrays.asList("App1", "App2", "App3");
}

private static List<String> getServerListFromDB() {
    try {
        TimeUnit.SECONDS.sleep((long) (Math.random() * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(Thread.currentThread().getName() + " getServer");
    return Arrays.asList("Server1", "Server2", "Server3");
}

您可以看到使用了默认的ForkJoinPool.commonPool,并且每个get*方法都是从该池中的单独线程执行的。您只需要在这些get*方法中运行SQL查询

链接中的答案会出现什么错误?.collectCollectors.toList.stream可以而且应该被忽略
ForkJoinPool.commonPool-worker-1 getServer
ForkJoinPool.commonPool-worker-3 getUser
ForkJoinPool.commonPool-worker-2 getAppList
[[Server1, Server2, Server3], [App1, App2, App3], [User1, User2, User3]]