简体   繁体   中英

How exactly does Java wait() method work?

Consider that thread 1 is running following code:

while (true) { 
    synchronized (this) {
        wait();
        ...Do Something ...
    }
}

And lets say we have thread 2 that notifies thread 1, ie:

synchronized (thread1)
    thread1.notify();
}

My question is lets say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running. Will thread1 run again when it finishes "do something"? Or will it just sleep instead?

Is my question clear enough?

Thank you.

Say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running. Will thread1 run again when it finishes "do something"? Or will it just sleep instead?

The latter. Primitive notify events are delivered to threads that are waiting at the time of the notify / notifyAll call. If no threads are waiting, the notify does nothing: the events are discarded.

Then is it possible to get wait queued? I would like to notify threads when new event happens, but will not like to have threads busy waiting... Is this possible?

Primitive notify events are not and cannot be queued.

If you need notifications to be queued, you will need to use a higher level concurrency class rather than wait / notify. For example Semaphore may do the job ... without busy waiting. Other possibilities are CyclicBarrier and CountdownLatch .

wait() works by purely halting the operation of a thread until another thread notifies it that it can continue running. A synchronized method is one that can only be run by one thread at a time.

A thread won't be 'notified' when it already running.

If a thread is running, and another thread notifies it, then the notify is "wasted" -- it has no effect. If the first thread calls wait() again, it will be returned into the wait pool as normal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM