有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程使Java方法不可中断的用例是什么

我在看谷歌番石榴。在等待新的许可证时,acquire方法将把线程置于uninterruptibleuninterruptible睡眠状态。中断异常

不间断的睡眠并不能完全忽略中断异常。但只要抓住它,记住它已经被打断,然后继续睡眠,直到达到超时。它最终会很好地将中断标志设置回线程

列表项

  • 这可以防止来电者通过中断来取消等待。它可能有什么好处?是否只是因为该方法不知道如何强制调用方处理InterruptedException
  • 我们可能希望使用相同模式的不间断代码的其他用例有哪些

编辑: 我才意识到我把它和错误的方法联系起来了

public static boolean awaitUninterruptibly(Condition condition, long timeout, TimeUnit unit)

正确的方法是不间断地睡眠

public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
    boolean interrupted = false;
    try {
      long remainingNanos = unit.toNanos(sleepFor);
      long end = System.nanoTime() + remainingNanos;
      while (true) {
        try {
          // TimeUnit.sleep() treats negative timeouts just like zero.
          NANOSECONDS.sleep(remainingNanos);
          return;
        } catch (InterruptedException e) {
          interrupted = true;
          remainingNanos = end - System.nanoTime();
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

共 (1) 个答案

  1. # 1 楼答案

    Is it just because the method doesn't what to force caller to handle InterruptedException

    呼叫者将不会收到InterruptedExceptionThread.currentThread().interrupt();只设置一个内部标志,它不会抛出InterruptedException

    可能有(我不知道是真的)情况下,等待而不被打断是有意义的。我确实知道一种理论上的中断可能会因为“虚假中断”而发生,即:没有真正原因的中断直接依赖于您的代码,如文档所示here

    When waiting upon a Condition, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics.