Wait for the wake-up mechanism in Java thorough explanation

State of the thread

First, look at what is the state of the thread, the thread state is that when a thread is created (new), and start (start), it is not a start to enter the execution state (run), nor is it always being executed.

Here to talk about Java's Thread class which has a State method, this method which covers the state of the six kinds of thread, as follows:

public  enum State {
     // not yet started a thread thread state. 
    NEW,

    // thread state runnable threads. 
    RUNNABLE,

    // thread state of the thread is blocked waiting for a monitor lock. 
    BLOCKED,

    // thread state of waiting threads. 
    WAITING,

    // with the specified waiting time waiting thread thread state. 
    TIMED_WAITING,

    // thread state to terminate the thread. 
    TERMINATED;
}

 

The six conditions leading to the occurrence of thread state

New - New

Thread just been created, but has not been started (the start method has not been called)

 

Runnable - run

Thread in a runnable state is executing in the Java virtual machine, but it may be waiting for additional resources from the operating system (eg processor).

 

Blocked - blocked by locks

When a thread lock want to get an object, but the object lock is held by another thread, the thread will be locked into the blocked state; when the thread holding the lock, the thread will become the state can run.

 

Waiting - wait indefinitely

When a thread a (wake up) another thread is waiting to perform in action, the thread goes into an infinite wait state. After entering this state it is not automatically wake up, to wait for another thread calls notify () method, or notifyall () method can only be awakened.

 

Timed_Waiting - timed wait

Similar to the infinite wait state, there are several methods timeout parameter, such as: Thread.sleep, Object.wait method. Call these methods, the timing to enter the wait state. Timing wait state will remain the timeout expires or receives a wake-up notification.

 

terminated - termination

1, because the normal exit run method of death.

2, because there is no capture of abnormal termination of the run method and death.

 

Cut waiting wake Case

Customers go to a restaurant for dinner, self-service orders, instructions what to eat, how much quantity. After the completion of orders, customers will wait for the hotel chef do the cooking, which is Waiting state (infinite wait state).

Cook received a single message, start cooking, prepare the meals, the food is handed on the desktop customers, customers to see the food has come (notify method), you can start to eat (wait wake-up mechanism).

 

Java code implementation (communication between threads)

analysis

Customers create a thread: the next single, the chef told what number of dishes, dishes to call the wait method, gives up the CPU into an infinite wait state (Waiting)

Creating a chef threads: see orders, took three seconds to do the food, well after the call notify method, customers wake up to eat.

note

Customers thread and thread chef, you must use the synchronization code block wrapped up, to ensure that there is a wait and wake up only in the implementation.

Lock synchronization objects used must be guaranteed to be unique.

Only lock object to be able to call Object.wait method and Object.notify method.

Code

public  class Demo01WaitNotify {
     public  static  void main (String [] args) {
         // create a lock object (to ensure unique lock) 
        Object Object = new new Object ();

        // create a thread Customers 
        new new the Thread () {
            @Override
            public  void RUN () {
                 // synchronous block wrapped to ensure that only one wake-up and wait in execution. 
                the synchronized (Object) {
                     // customer orders 
                    System.out.println ( "I want a city west Rainbow fried tomatoes, fried potatoes, a potato, rice bowls" );
                     // call the wait method, gives up the CPU, into infinite wait state (waiting) 
                    the try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace ();
                    }
                    // After waking up (after meal came), eat! ! ! Really fragrant. 
                    System.out.println ( "I'm starving to death, jump from here, you will not eat a morsel of food ... so delicious !!!!" );
                }
            }
        }.start();

        // create a thread cook 
        new new the Thread () {
            @Override
            public  void RUN () {
                 // Cook received orders request, take three seconds to food, cooked 
                the try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                // use synchronized block wrapped up, to ensure that there is a wait and wake up only in the implementation. 
                the synchronized (Object) {
                    System.out.println ( "My food is to do the three seconds, Wu Shi oh you eat?" );
                     // After done, notify method calls, wake-up customers to eat. 
                    object.notify ();
                }
            }
        }.start();
    }
}
Console output:
I want a city west Rainbow fried tomato, a potato fried potatoes, two bowls of rice
My meal three seconds well, oh Wu Shi you eat?
I was starved, jump from here, you will not eat a meal. . . Really fragrant! ! ! !

 

The above code, there is a communication between threads, then what is the communication between threads it? Simply put, that is, multiple threads working on the same resource, but the action (threaded task) process is different. As chef at cooking thread, the thread Customers eat vegetables. Why To communicate between threads it? When concurrent execution of multiple threads, default CPU is randomly switching threads, multiple threads when we need to work together to complete a task, and you want them to perform regularly, then you need to multi-thread between Some coordination of communication, to achieve a multi-threaded interoperable data.

 

Code communication in understanding:

And no food to be judged -

1, no meals (False).

2, the customer orders.

3, the chef at cooking.

4, the thread waits for customers.

5, chefs prepare the meals

6, modify the state of the food (True)

7, there is food, chef thread thread remind customers to eat vegetables.

8, cooks thread waits

9, eating meals, meals modified state (False)

This is the communication between the customer and the chef threads thread. By analogy, other Java programs communicate multiple threads is the same reason.

 

 

Wait for the wake-up mechanism in Java to resolve here, and if there are any deficiencies, wrong place, hope bigwigs correction.

Guess you like

Origin www.cnblogs.com/liyihua/p/12216197.html