English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Introduction to java Object wait Method

java Object wait method

When thread B tries to access a shared resource, it wants to acquire the lock object of the resource, but finds that the lock has already been obtained by thread A. In this case, thread B can only be suspended and wait for thread A to release the lock.

But thread A, which has obtained the lock, does not want to continue executing due to some conditions not being met and prefers to wait first (note: it is thread A that wants to actively wait, having already obtained the lock), hoping to continue executing the task after a certain condition is met. In the synchronized code block, thread A must first release the lock before thread B can be qualified to obtain the lock, enter the synchronized code block, and execute the code. After thread B has finished executing, the conditions that thread A needs have been met, so at this point, there must be a notification mechanism to allow thread A to transition from a waiting state to an execution state and continue executing the code.

Some students think that thread A can also keep looping and checking whether the condition is satisfied without necessarily interrupting itself and waiting. In fact, this is also a kind of thinking, but what about it? It is very CPU-consuming, and it is also not known when the condition can be satisfied.

To coordinate and communicate between threads, there must be a waiting mechanism and a notification mechanism, in JAVA, it corresponds to the wait method and notify method.

Object's wait method

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

If you want thread A to be in a waiting state, you can call the wait method of the current object. Once the wait method is called, it means: thread A has obtained the lock, and has done all that can be done, now it can only wait, waiting for other synchronized operations to execute some code after which I will come back to continue working.

Note:

The wait method is defined on the root class Object, Thread inherits from the Object class, so it naturally also has the wait method. But here it is not calling the wait method of the current thread object, but the wait method of the current object with lock properties; this point is also not very clear to me, I think it can be done by using the wait method and notify method of thread A, but it is estimated to be very麻烦. In addition, from the perspective of the scene, wait is defined on Object is also reasonable, indicating that the thread is hung in the object's waiting pool.

Thank you for reading, I hope it can help everyone, thank you for your support to this website!

You May Also Like