Java_object_wait (), notify (), Notifyall ()

Source: Internet
Author: User

this blog post for the original, reproduced please specify the source! http://blog.csdn.net/zimo2013/article/details/401813491. Overview

In the same process, multiple threads can be created to share the same block of data space, and the Java language provides a special mechanism to effectively avoid the same data object being accessed by more than one thread at the same time.

Among them, wait and notify is an important part of the Java synchronization mechanism, and it is necessary to combine with synchronized keyword to build many excellent synchronization models. When you invoke the wait and Notify/notifyall of an object, you must ensure that the calling code is synchronous to the object, meaning that it must be equal to synchronized (obj) {...} To call obj's wait and Notify/notifyall three methods, or you will get an error: Java.lang.IllegalMonitorStateException:current thread not owner

The purpose of wait is to expose the object lock , so it is necessary to ensure that the lock.wait () method is called in the Sync Code of lock , so that other threads can wake up the thread waiting for the object in the pool by notify the object. The same notify also releases the object lock, which must obtain the lock of the object before it is called, otherwise it will also report an exception. Therefore, the thread automatically releases its possession of the object lock, will not go to apply for object lock, only when the threads are awakened or to reach the maximum sleep time, it is again to fight for the object lock rights.


2. Main methods
(1). Wait ()

Wait for the object's synchronization lock, need to obtain the object's synchronization lock to call this method, otherwise the compilation can pass, but the runtime will receive an exception: Illegalmonitorstateexception. Calling the Wait () method of an arbitrary object causes the thread to block, the thread cannot continue execution, and the lock on the object is freed.

(2). Notify ()

Wake up the thread waiting for the object to synchronize the lock (wake only one, if there are multiple waits), note that when this method is called, it does not wake up the thread of a waiting state exactly, but is determined by the JVM to wake up which thread, and not by priority. Calling the Notify () method of an arbitrary object causes a randomly selected unblocking in a thread that is blocked by calling the wait () method of the object (but is not really executable until the lock is acquired).

(3). Notifyall ()

Wake up all waiting threads, notice that the thread that wakes up is notify before wait, and has no effect on the wait thread after notify.

In general, there is a need for coordination between multithreading: if the condition is not met, wait, and when the condition is met, the thread that waits for the condition is awakened. In Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism.


3. Example

public class Main {private static Object lock = new Object ();p ublic static void Main (string[] args) {new Thread () {@Overri depublic void Run () {try {synchronized (lock) {System.out.println (Thread.CurrentThread () + ", get the Lock" + New Date (). g Etseconds ()); lock.wait (10 * 1000); System.out.println (Thread.CurrentThread () + "," + New Date (). getseconds ());}} catch (Interruptedexception e) {e.printstacktrace ();}}}. Start (); try {System.out.println ("11111111"); Thread.Sleep (2 * 1000); System.out.println ("2222222"); synchronized (lock) {System.out.println (Thread.CurrentThread () + ", get the lock" + new Date (). getseconds ()); Lock.notify (); System.out.println ("lock.notify ();"); Thread.Sleep (5 * 1000); System.out.println (Thread.CurrentThread () + "End");}} catch (Interruptedexception e) {e.printstacktrace ();} /* * 11111111thread[thread-1,5,main], get the lock172222222thread[main,5,main], get the lock19lock.notify (); thread[main,5,main]endthread[thread-1,5,main],24 */}}

4. Common Errors

(1). Occurrence of Java.lang.IllegalMonitorStateException

Whether wait (), notify (), Notifyall () are running in the synchronization lock for that object

public class Main {private static Object lock = new Object ();p ublic static void Main (string[] args) {//invalid 1synchronized (Ma In.class) {try {lock.wait ()} catch (Interruptedexception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();}} Invalid 2try {lock.wait ();} catch (Interruptedexception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();}}}

(2). Java.lang.IllegalMonitorStateException:object not locked by thread before notify ()

public class Main {private static Object lock = new Object ();p ublic static void Main (string[] args) {new Thread () {@Overri depublic void Run () {try {synchronized (lock) {lock.wait (ten *);}} catch (Interruptedexception e) {e.printstacktrace () ;}}}. Start (); try {thread.sleep (2 *); synchronized (lock) {//lock Lock has been re-assigned lock = new Object (); Lock.notify ();}} catch ( Interruptedexception e) {e.printstacktrace ();}}}


Java_object_wait (), notify (), Notifyall ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.