Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the wait and notify method in Java Thread?

I'm very confusing about these two descriptions:

  1. "The wait method blocks the calling thread and gives up the monitor lock"
  2. "The notify method unblocks one waiting thread but does not give up the monitor lock"

Here is my questions:

  1. I know each object in Java has a lock, but what is the "monitor lock" means? is it the same as the oject's lock?

  2. Why notify method needs to give up the monitor lock?

  3. If I try to make a object waiting 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, is that means the the current object is blocked by synchronized keyword, and then wait method releases the lock?

like image 399
Haoming Zhang Avatar asked Jan 01 '12 07:01

Haoming Zhang


1 Answers

I know each object in Java has a lock, but what is the "monitor lock" means? is it the same as the object's lock?

Yes, they are the same thing. They are also occasionally called the object's "mutex" and the object's "primitive lock". (But when someone talks about Lock, they are talking about this Java interface ... which is a different locking mechanism.)

Why notify method needs to give up the monitor lock?

The notify method doesn't give up the lock. It is your code's responsibility to give up the lock (i.e. leave the synchronized block or return from the synchronized method) after the notify call returns.

Why is that necessary? Because any other thread that is currently waiting on that lock (in a wait(...) call) has to reacquire that lock before the wait call can complete.

Why did they design notify / wait like this? So that they can be used to implement condition variables.

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

That is correct. When a thread calls someObject.wait() its lock on someObject is released ... and then reacquired (by the same thread) before the wait() call returns. Of course, in the meantime the lock someObject may have been acquired and released multiple times by other threads. The point is that when wait returns, the thread that called wait will have the lock.

like image 179
Stephen C Avatar answered Oct 14 '22 08:10

Stephen C