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

时间:2018-01-20 06:00:23

标签: concurrency parallel-processing java-8

我有3个方法返回结果列表,我的sql查询在每个方法中执行并返回结果列表。我想要并行执行所有3个方法,所以它不会等到完成一个和另一个。我看到一个stachoverflow帖子,但它没有工作。 该链接是[How to execute multiple queries in parallel instead of sequentially? [Execute multiple queries in parallel via Streams

我想解决使用java 8的功能。 但以上链接如何调用多种方法请告诉我。

1 个答案:

答案 0 :(得分:0)

Execute multiple queries in parallel via Streams适用于您的任务。以下是演示它的示例代码:

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-worker-1 getServer
ForkJoinPool.commonPool-worker-3 getUser
ForkJoinPool.commonPool-worker-2 getAppList
[[Server1, Server2, Server3], [App1, App2, App3], [User1, User2, User3]]

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

中运行SQL查询