java - 在for循环里使用多线程查询数据库

查看:2217
本文介绍了java - 在for循环里使用多线程查询数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

现在是需要在循环去查询数据库,然后进行数据汇总。大家有例子,建议参考意义吗

解决方案

其实如果你是因为每个查询任务都比较慢,所以想采用这种方式,不如去优化一下sql。或者你可以用下面的这种线程池的方式来处理,不过代码的复杂度会大大提高的。
Futrue返回的包装的数据类型对应你sql返回的类型
或者你可以使用fork/join来处理

public class CallableAndFuture {
    
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 10; i < 15; i++) {
            futures.add(threadPool.submit(new Task(i)));
        }
        try {
            Thread.sleep(1000);// 可能做一些事情

            int allSum = 0;
            for (Future<Integer> f : futures) {
                int fsum = f.get();
                System.out.println("sum:" + fsum);
                allSum += fsum;
            }
            System.out.println("allSum:" + allSum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
    }
}


class Task implements Callable<Integer> {
    private int i;

    public Task(int i) {
        this.i = i;
    }

    @Override
    public Integer call() throws Exception {
        // 替换成db的查询
        int sum = 0;
        for (int j = 0; j <= i; j++) {
            sum += j;
        }
        return sum;
    }

}

这篇关于java - 在for循环里使用多线程查询数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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