Waiting and wake-up mechanism (communication between threads)

Inter-thread communication

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

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, and we want them to have the implementation of the law, it requires some coordination of communication between so many threads, in order to help us achieve an interoperable multi-threaded data.

How to ensure the efficient use of resources for communication between threads:

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. That is, multiple threads operating the same data, to avoid competition for the same shared variable. That is, 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: It 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. Like in the company that you and your colleagues, you may be present at the promotion of competition, but more often you more to work together to accomplish certain tasks. After the thread is in a predetermined operation, enters the standby state (wait ()), waiting for their execution after the completion of the specified code then other threads its wake (notify ()); when there are multiple threads waiting, if necessary, use notifyAll () to wake up all waiting threads. wait / notify is a collaborative mechanism among threads.

Waiting in the wake method

Wait for the wake-up mechanism is used to solve the problem of communication between threads, meaning the use of three methods are as follows:
  • 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
  • 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.
  • notifyAll: All threads on the notification object wait set is released.
note:
  • Even if only to inform a waiting thread, the thread can not be notified to resume execution immediately, because it had interrupted the place is in sync blocks, but at the moment it no longer holds the lock, so she needs to try to acquire the lock again (probably faced with competition from other threads) to resume execution in place after the original method after a successful call to wait.
Summarized as follows:
  • If you can get a lock, the thread changes from WAITING state RUNNABLE 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
  • 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.
  • notify and wait 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.
  • notify and wait method must be used in the method of synchronization code block or a synchronizing function. Because: must call this method through two lock object.

Producer and consumer issues

Wait for the wake-up mechanism is actually a classic "producer-consumer" problem.
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 of the case depends on the lock.
note:
Baozi Pu and buns thread is -> Communications mutually exclusive. Must use synchronization techniques to ensure that only one thread in execution
Lock object is unique. You can use the object as a lock object buns
Bao Zipu class and classes need bun buns objects passed in as a parameter
  1. We need to create a bun variable in the member variable position
  2. Use parameters configured to assign buns
Buns resource categories:
Package demo01; 

public  class baozi { 
        String PI; 
        String Xian; 
        Boolean In Flag = to false ; // whether the resource exists steamed buns resource status 
    }
Baozi Pu thread class:
Package Penalty for demo01; 

public  class BaoZiPu the extends the Thread {
     // need to create the position of a member variable variable bun 
    Private Baozi bz;
     // use configuration parameters for variable assignment 

    public BaoZiPu (String name, Baozi bz) {
         Super (name);
         the this = .bz BZ; 
    } 
    // set the task threads, buns produced 

    @Override 
    public  void RUN () {
         int COUNT = 0 ; 

        the while ( to true ) {
             // synchronize 
            the synchronized (BZ) {
                 IF(== bz.flag to true {) // presence bun resources 
                    the try {
                         // thread enters a wait time 
                        bz.wait (); 
                    } the catch (InterruptedException E) { 
                        e.printStackTrace (); 
                    } 
                } 
                // do not make steamed buns 
                System .out.println ( "start Bao Zipu baking" );
                 IF (COUNT% 2 == 0 ) {
                     // snowy Nuts 
                    bz.pi = "snowy" ; 
                    bz.xian = "Nuts" ;
                } The else {
                     // crust beef onion 
                    bz.pi = "thin-skinned" ; 
                    bz.xian = "beef, onion" ; 
                } 
                COUNT ++ ; 

                the try {
                     // . 5 seconds buns produced 
                    the Thread.sleep (5000 ); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 
                // production well modified state 
                bz.flag = to true ; 
                System.out.println ( "bun made good:" + + bz.pi bz.xian);
                System.out.println ( "eat goods to eat" );
                 // wake up waiting threads (food goods) 
                bz.notify (); 
            } 
        } 

    } 
}
Food goods thread class:
package demo01;

public class Eat extends Thread {
    private baoZi bz;

    public Eat(String name, baoZi bz) {
        super(name);

        this.bz = bz;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (bz) {
                if (bz.flag == true) {
                    System.out.println("我在吃包子");
                    //3秒吃完
                    try {
                        Thread.sleep ( 3000 ); 
                    } the catch (InterruptedException E) { 
                        e.printStackTrace (); 
                    } 
                    System.out.println ( "I ate" );
                     // finished buns modified state 
                    bz.flag = to false ;
                     // eat over, wake baking threads 
                    bz.notify (); 
                    System.out.println ( "fast do buns" ); 
                } 
            } 
        } 
    } 
}

Test category

package demo01;

public class Eat extends Thread {
    private baoZi bz;

    public Eat(String name, baoZi bz) {
        super(name);

        this.bz = bz;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (bz) {
                if (bz.flag == true) {
                    System.out.println("我在吃包子");
                    //3秒吃完
                    try {
                        Thread.sleep ( 3000 ); 
                    } the catch (InterruptedException E) { 
                        e.printStackTrace (); 
                    } 
                    System.out.println ( "I ate" );
                     // finished buns modified state 
                    bz.flag = to false ;
                     // eat over, wake baking threads 
                    bz.notify (); 
                    System.out.println ( "fast do buns" ); 
                } 
            } 
        } 
    } 
}

Results of the

Baozi Pu began to do buns 
buns made good: Snowy Nuts 
eat goods to eat 
my bun 
I finished 
fast to do buns 
Baozi Pu began to do buns

 

 

Guess you like

Origin www.cnblogs.com/wurengen/p/10929821.html