search

Home  >  Q&A  >  body text

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

黄舟黄舟2770 days ago1020

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:39:57

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

    reply
    0
  • Cancelreply