java multithreaded wait, notify / notifyAll difference

1, wait (), notify / notifyAll () method is a local final Object methods, it can not be rewritten.
 
2, wait () so that the current thread blocked, the prerequisite is to first obtain a lock, generally synchronized with keywords, i.e., generally used wait () in the block having the synchronization code synchronized, notify / notifyAll () method.
 
3, since the wait (), notify / notifyAll () in the synchronized block of code, instructions must be the current thread acquired the lock.
When the thread executing wait () method when the current lock is released, and then let the CPU, enter the wait state.
Only when the notify / notifyAll () is executed when will wake up one or more threads are in a wait state, and then continue down until you execute the code synchronized code block or halfway encountered wait (), released again lock.
In other words, notify / notifyAll () is executed only awaken threads, without releasing the lock immediately, release depends on the specific implementation of the code block lock. Immediately after it exits the critical region in the programming, try to use the notify / notifyAll (), let it get to wake up other threads lock
 
4, wait () try catch needs to be surrounded by so abnormal interruption can also make a thread wait waiting wake.
 
5, the order can not be wrong notify and wait, if A first thread execution notify method, thread execution wait method B, then thread B can not be awakened.
 
6 difference, notify and notifyAll of
notify method only wake up a waiting thread (object) and the thread begins execution. So if there are multiple threads waiting on an object, this method will only wake up one thread, the choice of which depends on the operating system threads to realize multi-thread management. notifyAll wakes up all the wait (objects) thread, despite which thread will first deal depends on the implementation of the operating system. If there are multiple threads in the current situation needs to be awakened, it recommended notifyAll method. For example, the producer - consumer use inside, every time need to wake up all consumers or producers, in order to determine whether the program can continue down

Guess you like

Origin www.cnblogs.com/sx66/p/11844645.html