【问题标题】:Thread.sleep() isn't pausing executionThread.sleep() 没有暂停执行
【发布时间】:2016-09-21 00:32:33
【问题描述】:

我试图通过 20 次尝试在每个循环中休眠 3,000 毫秒,将循环中的进程尝试限制为 60 秒。调用 Thread.sleep() 实际上并没有暂停正在运行的线程中的执行,而是所有 20 次尝试连续快速发生。

private void pollWebServiceForToken() {
    final int pollInterval = 3000;
    new Thread() {
        @Override
        public void run() {
            int attempts = 0;
            int maxAttempts = 60;
            String token;
            do {
                token = requestToken(exchangeCode);
                if (token.contains(FAILED)) {
                    try {
                        Thread.sleep(pollingInterval);
                    } catch (InterruptedException ex) {
                        this.currentThread().interrupt();
                    }
                }
                attempts++;
            } while (token.toLowerCase().contains(FAILED) && attempts < maxAttempts && !cancelled);
        }
    }.start();
}

由于这一切都发生在 Vaadin 应用程序内部,我假设错误的线程被置于睡眠状态,但我不确定如何针对特定线程进行睡眠。

提前致谢

【问题讨论】:

  • InterruptedException 发生了吗?
  • 不,它几乎立即运行了所有 20 次尝试 = /
  • 在InterruptedException catch-handler 中中断当前线程究竟有什么意义?
  • 通常,当您在线程中看到InterruptedException 时,您应该中断任何处理并允许线程终止。在 catch 块的末尾添加 break; 会有所帮助。与您的问题无关,只是最佳实践。
  • 谢谢大家。这是我第一次必须穿线任何东西,所以我仍然需要了解细微差别=)

标签: java multithreading vaadin sleep thread-sleep


【解决方案1】:

您确定 if 中的代码正在运行吗? while 的条件不同(+toLowerCase)。 Thread.sleep() 总是导致当前线程休眠。

【讨论】:

  • 哎呀,太尴尬了。感谢您为如此愚蠢的疏忽节省了我一个小时!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 2015-03-05
  • 2019-02-01
相关资源
最近更新 更多