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

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

阅读 12.9k
1 个回答

其实如果你是因为每个查询任务都比较慢,所以想采用这种方式,不如去优化一下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;
    }

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题