The java Object wait method is described in detail

  • 2020-06-07 04:36:31
  • OfStack

java Object wait method

When thread B accesses a Shared resource, it tries to obtain the lock object of the resource and finds that the lock has been obtained by thread A. At this time, thread B can only be suspended and wait for thread A to release the lock.

However, during the process of execution, the thread A with the lock does not want to continue execution for the time being because some conditions are not met. It wants to wait for 1 first (note: it is the thread A with the lock that wants to actively wait), and it wants to continue to execute the task after a certain condition is met. In the synchronized block, thread A must first release the lock before thread B is eligible to acquire the lock, enter the synchronized block, and execute the code. After the thread B finishes executing, the condition required by thread A has been satisfied, then at this time, there must be a notification mechanism to make thread A change from waiting state to execution state, and continue to execute the code.

Some students think that thread A can also be 1 straight loop judgment, check whether the condition has been met, but not 1 must interrupt itself, and then wait. That's actually one way to think about it, but what? CPU is expensive, and it is not known when the condition will be met.

To coordinate communication between threads, there must be a waiting mechanism and a notification mechanism, which in JAVA correspond to wait and notify methods.

Object's wait method


 
synchronized (obj) {
    while (condition does not ok){
      obj.wait();
    }
 }

If you want to keep thread A in a wait state, you can call the current object's wait method. Once the wait method 1 is called, it means that thread A has acquired the lock, has done everything it can, and is now waiting for some code to be executed by another synchronization operation before I return to work.

Note:

The wait method is defined on the root class Object, which inherits from the Object class, and there are also wait methods. But instead of calling the wait method of the current thread object, it's the wait method of the current object with the lock attribute. I don't quite understand this point either. I think it is actually possible to use the wait and notify methods of thread A to switch to the waiting state and then wake up, but it is probably very difficult to implement. In addition, from the perspective of scenario, wait is defined in Object, which means that the thread is hanging in the object's wait pool.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: