Examine Java threads wait and notify in detail

  • 2020-04-01 04:05:28
  • OfStack

Wait () and notify() are directly subordinate to the Object class, which means that all objects have this pair of methods. This may seem strange at first, but it's actually quite natural, because this pair of methods blocks to release the occupied lock that any object has, and calling the wait() method on any object causes the thread to block and the lock on that object to be released. Calling the notify() method on any object causes a randomly selected thread that is blocked by calling the object's wait() method to unblock (but not actually execute until the lock is obtained).

Second, wait() and notify() can be called from anywhere, but this pair of methods must be called in a synchronized method or block, for the simple reason that only the current thread in the synchronized method or block holds the lock and can release it. By the same token, the lock on the object calling this pair of methods must be owned by the current thread in order for the lock to be released. Therefore, method calls must be placed in such a synchronized method or block that the locked object of the method or block is the object on which the methods are called. If they do not meet this one thing, the program, though still able to compile, but abnormal IllegalMonitorStateException at run time.

  Wait () and notify () method of the above features determines they often use, together with a synchronized method or block them and inter-process communication mechanism of the operating system you will find a comparison of their similarities: a synchronized method or block provides a similar to the function of the operating system primitives, their execution will not be multi-threaded mechanism of the interference, and the laws of the other party is equal to the block and wakeup primitives (the two methods are declared as synchronized). Their combination allows us to implement a series of sophisticated interprocess communication algorithms (such as semaphore algorithms) on the operating system and to solve various complex interthread communication problems.
 

Two last points about the wait() and notify() methods:
      First: the thread that unblocked by calling the notify() method was randomly selected from the thread that blocked by calling the object's wait() method, and we can't predict which one will be selected, so we have to be careful when programming to avoid problems with this uncertainty.
      Second: in addition to notify(), there is a method, notifyAll(), that performs a similar function, except that calling the notifyAll() method unblocks all the threads that were blocked by calling the object's wait() method at once. Of course, only the thread that acquired the lock can enter the executable state.

Demo for related wait and notify:


/**
 * <pre>
 *  Subthread loop 10 And then the main thread loop 100 Then there is a return to the child thread loop 10 Time, 
 *  Then return to the main thread loop 100 Time, so executed 50 time 
 * </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 <= 50; i++) {
           business.sub(i);
         }
 
       }
     }).start();
 
     for (int i = 1; i <= 50; 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 <= 10; j++) {
       System.out.println("sub thread sequence of " + j + ",loop of " + i);
    }
     isMainThread = false;
     this.notify();
   }
 
  public synchronized void main(int i) {
     while (isMainThread) {
       try {
        this.wait();
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
     for (int j = 1; j <= 100; 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 it.


Related articles: