wait (), notify () method works, and Cautions

wait, notify principle

        When it comes to the front by the nature of the object lock is actually a data structure of the monitor lock object header. The structure is as follows:

(Photo from Internet)

Competitors with several thread-locking (enter), only one can succeed (acquire), a successful record in the thread The Owner structure. Call wait, notify operation process is as follows:

       (1) An existing objects o, the lock is being held by a thread t1, call wait () method, the thread will be t1 "to dry" (actually just recorded) Wait Set structure.

       (2) then there will be another thread to acquire the lock t2, The Owner records into a thread t2.

       (3) t2 thread does not need o the lock , the call o.notify () / o.notifyAll () method, the thread will tell who object o Wait Set structure recorded: Since you compete but also my friends, my lock now not being holders.

Simply put, it is: wait notify the holder of the object is locked myself in my thread to release the lock, notify () / notifyAll () is the object of the notification just been crowded out of their own thread but also competition since my lock. I think a more appropriate analogy:

        Guests (thread) to visit the owner (subject), the owner must obtain the right time (lock), and the owner received only one person at the same time (mutual exclusion).

        When the living room is a guest reception, for some reason, the owner must be received another guest, then the host invited guests to the current waiting room to another room, so that their time right (wait method)

        Owner in the living room another guest reception, after the reception is finished, let a former (and possibly several) and then to the living room waiting for the guests in the other room, and continued to receive (notify / notifyAll method)

 

wait, notify sync block to be placed

      Actually very simple, if not in sync block, the thread did not achieve target lock, and talk about how to make an object notification thread releases the lock, or lock it to compete? Perhaps a notice to the Main thread. If you do not put a synchronized block, it will produce Lost-wake problem, namely the loss of wake, consumers more than a producer for example:

 

       Producer thread found a box full of determining must wait, but because the wait is not in sync blocks, because the producer thread at this time did not wait.

       Consumer thread calls notify () method after consumption of a product from the buffer, the last notify messages will be ignored.

       Producer thread calls the wait () method and enters a wait state, not informed.

Therefore, due to the conditions of competition here, we may notice a loss, if we use a buffer or only one product, the producer thread will wait forever, your program will hang up.

 

Guess you like

Origin www.cnblogs.com/shen-qian/p/11265631.html