Home > Java > javaTutorial > body text

Detailed explanation of wait/notify instances of communication between Java threads

怪我咯
Release: 2017-06-30 10:48:54
Original
1452 people have browsed it

The following editor will bring you a brief discussion of wait/notify communication between Java threads. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

wait/notify/notifyAll in Java can be used to implement inter-thread communication. It is a method of Object class. These three methods are all native methods. It is platform dependent and is often used to implement the producer/consumer pattern. First, let’s take a look at the relevant definitions:

wait(): The thread calling this method enters the WATTING state and will only wait for notification or interruption from another thread. Return, after calling the wait() method, the object's lock will be released.

wait(long): Timeout waits for up to long milliseconds. If there is no notification, it will timeout and return.

notify(): Notify a thread waiting on the object to return from the wait() method, and the premise of return is that the thread obtains the object lock.

notifyAll(): Notify all threads waiting on this object.

A small example

Let’s simulate a simple example to illustrate. We have a small dumpling restaurant downstairs and the business is booming. , there is a chef and a waiter in the store. In order to avoid that every time the chef prepares a portion, the waiter takes out one portion, which is too inefficient and wastes physical energy. Now assume that every time the chef prepares 10 portions, the waiter will serve it to the customer on a large wooden plate. After selling 100 portions every day, the restaurant will close and the chef and waiters will go home to rest.

Think about it, to implement this function, if you do not use the waiting/notification mechanism, then the most direct way may be that the waiter goes to the kitchen every once in a while and takes out 10 servings on a plate.

This method has two big disadvantages:

#1. If the waiter goes to the kitchen too diligently, the waiter will be too tired. , it is better to serve a bowl to the guests every time you make a bowl, and the role of the big wooden plate will not be reflected. The specific manifestation at the implementation code level is that it requires continuous looping and wastes processor resources.

2. If the waiter goes to the kitchen to check after a long time, timeliness cannot be guaranteed. Maybe the chef has already made 10 servings, but the waiter did not observe it.

For the above example, it is much more reasonable to use the waiting/notification mechanism. Every time the chef makes 10 servings, he will shout "The dumplings are ready and can be taken away." When the waiter receives the notification, he goes to the kitchen to serve the dumplings to the guests; the chef has not done enough yet, that is, he has not received the notification from the chef, so he can take a short rest, but he still has to prick up his ears and wait for the notification from the chef.

package ConcurrentTest;

import thread.BlockQueue;

/**
 * Created by chengxiao on 2017/6/17.
 */
public class JiaoziDemo {
  //创建个共享对象做监视器用
  private static Object obj = new Object();
  //大木盘子,一盘最多可盛10份饺子,厨师做满10份,服务员就可以端出去了。
  private static Integer platter = 0;
  //卖出的饺子总量,卖够100份就打烊收工
  private static Integer count = 0;

  /**
   * 厨师
   */
  static class Cook implements Runnable{
    @Override
    public void run() {
      while(count<100){
        synchronized (obj){
          while (platter<10){
            platter++;
          }
          //通知服务员饺子好了,可以端走了
          obj.notify();
          System.out.println(Thread.currentThread().getName()+"--饺子好啦,厨师休息会儿");
        }
        try {
          //线程睡一会,帮助服务员线程抢到对象锁
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println(Thread.currentThread().getName()+"--打烊收工,厨师回家");
    }
  }

  /**
   * 服务员
   */
  static class Waiter implements Runnable{
    @Override
    public void run() {
      while(count<100){
        synchronized (obj){
          //厨师做够10份了,就可以端出去了
          while(platter < 10){
            try {
              System.out.println(Thread.currentThread().getName()+"--饺子还没好,等待厨师通知...");
              obj.wait();
              BlockQueue
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          //饺子端给客人了,盘子清空
          platter-=10;
          //又卖出去10份。
          count+=10;
          System.out.println(Thread.currentThread().getName()+"--服务员把饺子端给客人了");
        }
      }
      System.out.println(Thread.currentThread().getName()+"--打烊收工,服务员回家");

    }
  }
  public static void main(String []args){
    Thread cookThread = new Thread(new Cook(),"cookThread");
    Thread waiterThread = new Thread(new Waiter(),"waiterThread");
    cookThread.start();
    waiterThread.start();
  }
}
Copy after login

Running result

cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--打烊收工,服务员回家
cookThread--打烊收工,厨师回家
Copy after login

Running mechanism

Borrowed from "ConcurrencyProgramming的Art》to understand the operating mechanism of wait/notify

Some people may be interested in the so-called monitor (monitor) , I don’t know much about object lock (lock). Here is a simple explanation:

jvm associates a lock with each object and class. Locking an object means obtaining the object. Associated monitors.

Only when the object lock is acquired can the monitor be obtained. If the lock acquisition fails, the thread will enter the blocking queue; if the object lock is successfully obtained, the wait() method can also be used to monitor Waiting on the server, the lock will be released and entered into the waiting queue.

Regarding the difference between locks and monitors, there is an article that is very detailed and thorough. I will quote it here. Interested children can learn more about it. Discuss the difference between locks and monitors in detail_Java Concurrency

According to the above figure, let’s take a look at the specific process

1. First, waitThread acquires the object lock, and then calls wait() method, at this time, the wait thread will give up the object lock and enter the object's waiting queue WaitQueue;

2. The notifyThread thread seizes the object lock, performs some operations, and calls the notify() method. At this time, the waiting thread waitThread will be moved from the waiting queue WaitQueue to the synchronized queue SynchronizedQueue, and the waitThread will change from the waiting state to the blocked state. It should be noted that notifyThread will not release the lock immediately at this time. It will continue to run and will only release the lock after completing its remaining tasks;

3. waitThread acquires the object lock again and starts from wait () method returns to continue performing subsequent operations;

4. An inter-thread communication process based on the wait/notification mechanism ends.

As for notifyAll, in the second step, all threads in the waiting queue are moved to the synchronization queue.

Avoid pitfalls

There are some special considerations when using wait/notify/notifyAll. Let me summarize them here:

1. Be sure to use wait( in synchronized )/notify()/notifyAll(), which means that the lock must be obtained first. We have mentioned this before, because the monitor can only be obtained after the lock is locked. Otherwise jvm will also throw IllegalMonitorStateException.

2. When using wait(), the condition to determine whether the thread enters the wait state must use while instead of if, because the waiting thread may be awakened by mistake, so while loop# should be used ##Check whether the wake-up conditions are met before and after waiting to ensure safety.

3. After the notify() or notifyAll() method is called, the thread will not release the lock immediately. The call will only move the thread in wait from the waiting queue to the synchronization queue, that is, the thread status changes from waiting to blocked;

4. The premise of returning from the wait() method is that the thread regains the calling object Lock.

Postscript

This is the introduction to wait/notify related content. In actual use, special attention should be paid to the above mentioned A few points, but generally speaking, we directly use wait/notify/notifyAll to complete inter-thread communication. There are not many opportunities for the producer/consumer model, because the Java concurrency package has provided many excellent and exquisite tools, such as various BlockingQueue and so on will be introduced in detail later when there is an opportunity.

The above is the detailed content of Detailed explanation of wait/notify instances of communication between Java threads. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!