How to understand the wait and notify methods in java thread?

I am very confused about these two descriptions:

>"Wait method blocks the calling thread and relinquishes the monitor lock > notify method unblocks a waiting thread without relinquishing the monitor lock"

This is my question:

>I know that every object in Java has a lock, but what does "monitor lock" mean? Is it the same as the lock of oject? > Why does the notification method need to relinquish the display lock? > If I try to make an object wait with the following code:

class simpleTask extends Thread
{
    int waitingTime;

    public simpleTask(int waitingTime)
    {
        this.waitingTime = waitingTime;
    }

    public void run()
    {
        synchronized(this) // this is a reference of current object
        {
        try {
            this.wait(waitingTime);
        } catch (InterruptedException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Like the first description above, it means that the current object is blocked by the synchronized keyword, and then the wait method releases the lock?

Solution

Yes, they are the same thing They are also occasionally referred to as "mutexes" of objects and "original locks" of objects (but when someone talks about lock, they are talking about this java interface... This is a different locking mechanism.)

The notify method does not relinquish the lock After the notification call returns, your code has the responsibility to relinquish the lock (that is, keep the synchronization block or return from the synchronized method)

Why is this necessary? Because any other thread currently waiting for the lock (in a wait (...) call) must reacquire the lock before waiting for the call to complete

Why do they design such notification / waiting? In this way, they can be used to implement conditional variables

That's right When a thread calls someobject When waiting (), it releases the lock of someobject... And then reacquires it (by the same thread) before the wait () call returns Of course, during this period, the locked someobject may have been acquired and released by other threads many times The key is that when wait returns, the thread calling wait will have the lock

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>