java - 在for循环里使用多线程查询数据库
黄舟
黄舟 2017-04-18 10:37:57
[Java讨论组]
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(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;
    }

}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号