Java thread state

 

package com.fgy.demo05;

/**
 * Wait wake Case: communication between threads
 * Note:
 * Use of sync lock object must be unique
 * Only lock object can call wait and notify () / notifyAll () method
 */
public class Demo1WaitAndNotify {
    public static void main(String[] args) {
        Object obj = new Object();

        new Thread() {
            @Override
            public void run() {
                synchronized (obj) {
                    System.out.println ( "Customers told to buns and number" );
                     the try {
                        obj.wait();
                        // obj.wait (5000); // if no wake-up after 5 seconds, it automatically wakes 
                    } the catch (InterruptedException E) {
                        e.printStackTrace ();
                    }
                    System.out.println ( "boss bun well, you can open eat" );
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep ( 5000); // takes 5 seconds baking 
                } the catch (InterruptedException E) {
                    e.printStackTrace ();
                }
                synchronized (obj) {
                    System.out.println ( "inform the customer, can a bun" );
                    obj.notify();
                }
            }
        }.start();
    }
}

Guess you like

Origin www.cnblogs.com/roadlandscape/p/12105203.html