java - 在for循环里使用多线程查询数据库
黄舟
黄舟 2017-04-18 10:37:57
0
1
1022
黄舟
黄舟

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

reply all(1)
小葫芦

In fact, if you want to use this method because each query task is relatively slow, it is better to optimize the SQL. Or you can use the following thread pool method to handle it, but the complexity of the code will be greatly increased.
The packaged data type returned by Futrue corresponds to the type returned by your sql
Or you can use fork/join to process

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;
    }

}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template