Detailed analysis of Java thread wait and Notify_java

Source: Internet
Author: User

Wait () and notify () are directly subordinate to the object class, which means that all objects have this pair of methods. At first glance this is incredible, but in fact it is natural, because this pair of methods is blocked to release the occupied lock, and the lock is any object has, the call of any object's wait () method causes the thread to block, and the lock on the object is freed. The Notify () method that invokes any object causes a randomly selected unblocking in a thread that is blocked by invoking the wait () method of the object (but not really executable until the lock is acquired).

Second, wait () and notify () can be invoked at any location, but this pair of methods must be invoked in the Synchronized method or block, and the reason is simple enough that a lock can be released only if the current line Cheng the lock in the Synchronized method or block. In the same way, the lock on the object that calls the method must be owned by the current thread so that the lock can be freed. Therefore, the method call must be placed in such a synchronized method or block, and the lock object of the method or block is the object that calls the methods. If this condition is not met, the program can still compile, but the illegalmonitorstateexception exception appears at run time.

The above characteristics of the wait () and notify () methods determine that they are often used in conjunction with synchronized methods or blocks, and that they and the operating system's interprocess communication mechanism A comparison will find their similarity: synchronized methods or blocks provide functionality similar to the operating system primitives, and their execution is not interfered by multithreaded mechanisms, which are equivalent to block and wakeup primitives (both of which are declared as Synchronized). Their combination enables us to implement a series of sophisticated interprocess communication algorithms (such as semaphore algorithms) on the operating system, and to solve the complex problem of communication between threads.

For the Wait () and notify () methods, the last two points are explained:
First: Calling the Notify () method causes the unblocked thread to be randomly selected from a thread that is blocked by calling the object's Wait () method, and we cannot anticipate which thread will be selected, so be careful when programming to avoid problems with this uncertainty.
Second: In addition to notify (), there is also a method Notifyall () can also play a similar role, the only difference is that the invocation of the Notifyall () method will block all threads that are blocked by calling the object's Wait () method at once. Of course, only the thread that gets the lock can enter the executable state.

Related wait and notify use Demo:

/** * <pre> * child thread Loop 10 times, then the main thread loop 100 times, then there are back to the child thread loop 10 times, * then back to the main thread loop 100 times, so 50 times * </pre> * @author KETQI * * public class Waitnotifydemo {public static void main (string[] args) {final Business Business = new Business ()
     ;
           New Thread (New Runnable () {@Override public void run () {for (int i = 1; I <= i++) {
         Business.sub (i);
 
     }}). Start ();
     for (int i = 1; I <= i++) {business.main (i);
 
   }} class Business {private Boolean ismainthread = true;
       Public synchronized void sub (int i) {while (!ismainthread) {try {this.wait ();
       catch (Interruptedexception e) {e.printstacktrace (); for (int j = 1; J <= J) {System.out.println ("Sub thread sequence of" + j + ", loop of" + I
    );
     } Ismainthread = false;
   This.notify (); synchronized void main (int i) {while (Ismainthread) {try {this.wait ();
       catch (Interruptedexception e) {e.printstacktrace ();  for (int j = 1; J <= J + +) {System.out.println ("main thread sequence of" + j + ", loop of" +
     i);
     } Ismainthread = true;
   This.notify ();
 }
 }

The above is the entire content of this article, I hope you can enjoy.

Related Article

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.