difference between wait() and yield()

前端 未结 3 1556
情歌与酒
情歌与酒 2021-02-14 23:02

So far what I have understood about wait() and yield () methods is that yield() is called when the thread is not carrying out any task and lets the CPU execute some other thread

3条回答
  •  臣服心动
    2021-02-14 23:40

    wait is for waiting on a condition. This might not jump into the eye when looking at the method as it is entirely up to you to define what kind of condition it is. But the API tries to force you to use it correctly by requiring that you own the monitor of the object on which you are waiting, which is necessary for a correct condition check in a multi-threaded environment.

    So a correct use of wait looks like:

    synchronized(object) {
      while( ! /* your defined condition */)
        object.wait();
      /* execute other critical actions if needed */
    }
    

    And it must be paired with another thread executing code like:

    synchronized(object) {
      /* make your defined condition true */)
      object.notify();
    }
    

    In contrast Thread.yield() is just a hint that your thread might release the CPU at this point of time. It’s not specified whether it actually does anything and, regardless of whether the CPU has been released or not, it has no impact on the semantics in respect to the memory model. In other words, it does not create any relationship to other threads which would be required for accessing shared variables correctly.

    For example the following loop accessing sharedVariable (which is not declared volatile) might run forever without ever noticing updates made by other threads:

    while(sharedVariable != expectedValue) Thread.yield();
    

    While Thread.yield might help other threads to run (they will run anyway on most systems), it does not enforce re-reading the value of sharedVariable from the shared memory. Thus, without other constructs enforcing memory visibility, e.g. decaring sharedVariable as volatile, this loop is broken.

提交回复
热议问题