有 Java 编程相关的问题?

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


共 (2) 个答案

  1. # 1 楼答案

    否。请改用^{},并确保在包含布尔值的对象上同步。如果不同步且boolean不是volatile,则没有内存障碍,因此无法保证轮询线程将看到对boolean的更改

    根据javadoc报告:

    This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

    • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
    • Some other thread invokes the notifyAll method for this object.
    • Some other thread interrupts thread T.
    • ...

    因此线程在等待通知时不会占用CPU

    下面的代码是一个简单的空闲标志,其中包含一个waitUntilIdle方法,您的main方法可以调用,另一个线程可以调用一个setIdle方法

    public class IdleFlag {
      private boolean idle;
    
      public void waitUntilIdle() throws InterruptedException {
        synchronized (this) {
          while (true) {
            // If the flag is set, we're done.
            if (this.idle) { break; }
            // Go to sleep until another thread notifies us.
            this.wait();
          }
        }
      }
    
      public void setIdle() {
        synchronized (this) {
          this.idle = true;
          // Causes all waiters to wake up.
          this.notifyAll();
        }
      }
    }
    
  2. # 2 楼答案

    我同意@Mike Samuel,但我建议您使用concurrent lock packages...

    继续mike的范例,用Java5中引入的锁替换他的锁

    更具体地说,您可以使用Condition'swait方法——那些需要超时的方法。例如,通过这种方式,您可以每隔一段时间记录一条消息,这条消息将帮助您调试无限等待。如果等待超时