Why should we use "bye" to check the race status, not "if",

I read the following code in "Thinking in java".

synchronized(obj)
    {
        while (condition_not_matched)
        {
            obj.wait();
        }
        //continue
        dosomething();

    }

What I think:
Use "if" in order, because "wait" means it should get the obj lock monitor, and only one thread can be executed here.

(1) Why use "while (condition)" not "if" here?
(2) What happened when executing "obj.wait ()"? Does a thread thread release the obj lock?
(3) And when another thread executed "obj.notify ()", what happened to the previous thread (did it restore obj lock or not? If so, then it must condition_not_matched, so "if" is enough.)
Am I wrong?

+4
source share
3 answers

The need for a loop is explained in Javadoc for methods wait:

, , -, . , , , , , .

, wait() , , wait() , . while.


wait(), , . , , notify() , , - , . , , notifyAll(), : wait(), , wait() ..

, , , , , , , false - , . , (, wait() ), , . ; , , .

: notifyAll() . , . , , , , , .

while .

+2

if , true false , , , .

as

A while while , . , , , .

obj.wait() - , notify() nofityAll() . , - , , .

obj.notify() , . , .

+1

if . .

- " ", , wait : , wait, . , , .

: , . , , . , , , , , . , -, , , , , , , , . while , , , , .

+1
source

Source: https://habr.com/ru/post/1612042/


All Articles