【问题标题】:Logging around a SQL query while its executing in java [closed]在java中执行SQL查询时记录它[关闭]
【发布时间】:2022-01-04 06:31:06
【问题描述】:

我有一个用 java 代码执行的 SQL 查询。

查询需要一段时间才能运行。大约 10 分钟。

我想在查询执行时添加一些重复的日志记录

类似于“查询正在执行 --- 请稍候”

如何做到这一点

【问题讨论】:

    标签: java multithreading logging execution


    【解决方案1】:

    Future、Callable 和 ExecutorService 有助于以安全的方式实现这一目标。

    您可以使用 ExecutorService 在单独的线程中运行查询,并使用 Future 对象来保存线程的返回值。 Future接口中有一个方法isDone(),当任务完成时返回布尔值true。

    继续循环打印“查询正在执行 --- 请稍候”,直到它返回 true。

    public class HelloWorldApp {
    
        public static void main(String... args) throws InterruptedException,
                ExecutionException {
    
            ExecutorService es = Executors.newSingleThreadExecutor();
    
            System.out.println("submitted callable task to calculate factorial of 10");
    
            Future result10 = es.submit(new FactorialCalculator(10));
            System.out.println("Is job done: " + result10.isDone());
            System.out.println("\n");
    
            do {
                System.out.println("loading...");
                Thread.sleep(1000);
            } while(!result10.isDone());
    
            System.out.println("\n");
            System.out.println("Is job done:" + result10.isDone());
    
            long factorial10 = (long) result10.get();
            System.out.println("factorial of 10 is : " + factorial10);
    
            es.shutdown();
        }
    
    }
    
    class FactorialCalculator implements Callable<Long> {
        private int number;
    
        public FactorialCalculator(int number){
            this.number = number;
        }
    
        @Override
        public Long call() throws Exception {
            return factorial(number);
        }
    
        private long factorial(int n) throws InterruptedException {
            long result = 1;
            while (n != 0) {
                result = n * result;
                n = n - 1;
                Thread.sleep(100);
            }
    
            return result;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多