Wait for the wake-up mechanism --- Day25

Inter-thread communication

  The concept: multiple threads working on the same resource, but the action (threaded task) is not treated the same.

  For example: A thread is used to generate the buns, for thread B bun, buns can be understood as the same resource, the thread A and thread B process operation, is a production and a consumption, then between the threads A and thread B there is thread communication problems.

  Why deal with inter-thread communication:

    When the concurrent execution of multiple threads, default CPU is randomly switching threads when multiple threads we need to work together to complete a task, we all know that according to the laws or rules are generally the implementation of tasks to perform, so much thread mission is the same, the need to coordinate communications law, in order to help us achieve interoperable multi-threaded task (piece of data).

  How to ensure the effective implementation of inter-thread communication tasks (resources):

    Multiple threads working on the same resource, and the task is not at the same time, the need to help solve thread communication between threads of the same variable or operation. Because multiple threads operating the same data, to avoid competition for the same shared variable. So we need to make sure each thread by means of effective use of resources. And this means that is - wait for the wake-up mechanism

Wait wake-up mechanism

  What is waiting for wake-up mechanism

    This is a collaborative mechanism among multiple threads. We often talked about the thread is conceivable competition between threads (race), such as a lock to compete, but this is not the whole story, there will be a cooperation mechanism between threads, a thread is in a predetermined operation after it enters the wait state (wait ()), waiting for other threads after the completion of the specified code and then execute their wake it up (notify ()); when there are multiple threads to wait, if necessary, use notifyAll () to wake up all waiting threads

    wait / notify is a collaborative mechanism between threads

Waiting in the wake method

  Wait for the wake-up mechanism is what is meant for the use of three methods to solve the problem of inter-thread communication is as follows

    1. wait: the thread is no longer active, no longer involved in scheduling, into the wait set, so do not waste CPU resources, not to compete lock, then thread state that is WAITING. It is also waiting for another thread to perform a particular action, that is, "to inform (notify)" on this object to wait for the release of the thread from the wait set out to re-enter the scheduling queue (ready queue) in

    2. notify: notify a thread object wait set is selected in the release; for example, the location of restaurants available, customers wait dining oldest first seated.

    3. notifyAll: all the threads on the notification object wait set is released.

    Note: even if only to inform a waiting thread, the thread can not be notified immediately resume execution, because where it originally was interrupted in the synchronized block, but at the moment it no longer holds the lock, so you need to try again to acquire the lock ( it is likely to face competition from other threads) to resume execution in place after the original call to wait to acquire the lock after successful method

  Summary: If you can get a lock, the thread becomes RUNNABLE status from WAITING state; otherwise, set out from the wait, and into the entry set, the thread from WAITING state and becomes BLOCKED state 

Call wait and notify methods need to pay attention to the details

  1. wait and notify methods method must be called by the same lock object. Because: the corresponding lock object can be woken notify the use of threads after the wait method call with a lock object.

  2. wait and notify method is a method belonging to the class of Object. Because: lock object can be any object, any object which belongs to the class are inherited Object class.

  3. wait and notify methods must be used in the method of the synchronization code is the synchronization block or function. Because: must call this method through two lock object.

Wait wake-up mechanism is "the relationship between producers and consumers."

  Take the production of consumer buns buns waiting wake-up mechanism for the effective use of resources:

    Baozi Pu thread production of buns, buns consumer food goods thread. When buns no time (buns state is false), food goods thread to wait Baozi Pu thread production dumplings (ie dumplings state is true), and notifies food goods threads (lift food goods wait state), as it has been buns, then Baozi Pu thread into a wait state. Next, eat goods thread can obtain further implementation of the case depends on the lock. If you eat the goods to get the lock, then the implementation of the action bun, bun eating (buns state is false), and notify the Baozi Pu thread (release wait state Baozi Pu), food goods thread into a wait. Baozi Pu thread can obtain further implementation depends on the lock case

Buns class

1  Package Penalty for demosummary.waitingandwake;
 2  
3  / ** 
4      Baozi Pu thread production of buns, buns consumer food goods thread. When there is no buns (buns state is false), food goods thread to wait
 5      Baozi Pu thread production of buns (ie buns state to true)
 6      and notify eat goods threads (lift food goods wait state), as it has been buns, then Baozi Pu thread into a wait state.
7      Next, eat goods thread can obtain further implementation of the case depends on the lock.
8      If you eat the goods to get the lock, then the implementation of the action bun, bun eating (buns state is false), and notify the Baozi Pu thread (release wait state Baozi Pu),
 9      food goods thread into the wait. Bao Zipu further execution depends on whether the thread acquiring the lock case
 10   * / 
. 11  public  class baozi {
 12 is      Private String PI;
 13 is      Private String Xian;
 14      Boolean In Flag = to false;
 15  
16      public baozi () {
 . 17      }
 18 is  
. 19      public baozi (PI String, String Xian, Boolean In Flag) {
 20 is          the this .pi = PI;
 21 is          the this .xian = Xian;
 22 is          the this .flag = In Flag;
 23 is      }
 24  
25      public String getPi () {
 26 is          return PI;
 27      }
 28  
29      public  void setPi (String PI) {
 30          the this .pi = PI;
 31 is     }
 32  
33 is      public String getXian () {
 34 is          return Xian;
 35      }
 36  
37 [      public  void setXian (String Xian) {
 38 is          the this .xian = Xian;
 39      }
 40  
41 is      public  Boolean isFlag () {
 42 is          return In Flag;
 43 is      }
 44 is  
45      public  void setflag ( Boolean In Flag) {
 46 is          the this .flag = In Flag;
 47      }
 48  
49     @Override
50     public String toString() {
51         return "BaoZi{" +
52                 "pi='" + pi + '\'' +
53                 ", xian='" + xian + '\'' +
54                 ", flag=" + flag +
55                 '}';
56     }
57 }

Baozi Pu category

. 1  Package demosummary.waitingandwake;
 2  
. 3  public  class BaoZiPu the extends the Thread {
 . 4      Private baozi BZ;
 . 5  
. 6      public BaoZiPu (String name, baozi BZ) {
 . 7          Super (name);
 . 8          the this .bz = BZ;
 . 9      }
 10  
. 11      @Override
 12 is      public  void RUN () {
 13 is          // define a variable to determine what skin and stuffed buns 
14          int COUNT = 0 ;
 15          the while ( to true) {
 16              the synchronized (BZ) {
 . 17                  IF (== bz.flag to true ) { // presence bun 
18 is                      the try {
 . 19                          bz.wait (); // enters a wait state, it does not require baking 
20 is                      } the catch (InterruptedException E ) {
 21 is                          e.printStackTrace ();
 22 is                      }
 23 is                  }
 24                  // no buns, buns Baozi Pu started 
25                  System.out.println ( "start Bao Zipu baking" );
 26                  // determines what buns 
27                  IF(COUNT = 0! ) {
 28                      // make ice egg yellow bun 
29                      bz.setPi ( "snowy" );
 30                      bz.setXian ( "egg yolk" );
 31 is                  } the else {
 32                      // do crust red bean paste 
33 is                      BZ. setPi ( "thin-skinned" );
 34 is                      bz.setXian ( "bean" );
 35                  }
 36                  COUNT ++ ;
 37 [                  // change of state has steamed bun 
38 is                  bz.flag = to true ;
 39                 System.out.println ( "bun done:" + bz.getPi () + bz.getXian () + " buns" );
 40                  System.out.println ( "Please wait for customers can come and collect buns" ) ;
 41 is                  bz.notify ();
 42 is              }
 43 is          }
 44 is      }
 45 }

Customers class

 1 package demosummary.waitingandwake;
 2 
 3 public class GuKe extends Thread{
 4     private BaoZi bz;
 5 
 6     public GuKe(String name, BaoZi bz) {
 7         super(name);
 8         this.bz = bz;
 9     }
10 
11     @Override
12     public void run() {
13         while (true) {
14             synchronized (bz) {
15                 if (bz.flag == false) {
 16                      the try {
 . 17                          bz.wait ();
 18 is                      } the catch (InterruptedException E) {
 . 19                          e.printStackTrace ();
 20 is                      }
 21 is                  }
 22 is  
23 is                  System.out.println ( "Customers get" + bz.getPi ( ) + bz.getXian () + "buns" );
 24                  bz.flag = to false ;
 25                  bz.notify ();
 26 is              }
 27          }
 28      }
 29 }

Test category

. 1  Package demosummary.waitingandwake;
 2  
. 3  public  class the Test {
 . 4      public  static  void main (String [] args) {
 . 5          // Create buns, Baozi Pu, customer objects 
. 6          baozi baozi = new new baozi ();
 . 7          BaoZiPu baoZiPu = new new BaoZiPu ( "Bao Zipu" , baozi);
 . 8          GuKe guKe = new new GuKe ( "customer" , baozi);
 . 9          // call the customer and Bao Zipu thread 
10          baoZiPu.start ();
 . 11          guKe.start ();
 12 is      }
 13 is }

 

Guess you like

Origin www.cnblogs.com/hpcz190911/p/11955116.html