【问题标题】:More elegant way to wait for a method result (with timeout) in Java 6在 Java 6 中等待方法结果(超时)的更优雅的方式
【发布时间】:2017-11-15 16:56:05
【问题描述】:

我正在尝试在 Java 6 中找到一种方法来等待来自读取数据库等待某些信息的方法的结果。

实际代码与此非常相似:

Result result = getSomeResult();
Long maxTries = 10;
Long sleepTimeInMs = 2000; // 10 tries and 2000 ms for each call is 20000 ms of timeout in total

int tries = 0;
while (tries < maxTries && (result == null || result.isProcessing())) {
    Thread.sleep(sleepTimeInMs);
    result = getSomeResult();
    tries++;
}

在上面的代码中,我不只是在等待结果;我正在等待 not null 结果并处于特定条件(未处理)。

谢谢!

【问题讨论】:

标签: java


【解决方案1】:

这是一种延迟运行部分代码的方法,您可以对其进行延迟

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
          //the action you want to do after reading database
        }
    }, delay_time);

或者你可以让你的读取数据库的方法“异步”

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 2019-11-03
    • 2021-08-31
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多