The difference between java sleep and wait methods

The main differences are as follows:

1. Each object has a lock to control synchronized access. The Synchronized keyword can interact with the object's lock to implement synchronized methods or synchronized blocks. The thread that is executing the sleep() method actively gives up the CPU (then the CPU can perform other tasks), and after the sleep specified time, the CPU returns to the thread to continue execution ( note: the sleep method only gives up the CPU, and The synchronous resource lock will not be released !!! ); The wait() method means that the current thread temporarily withdraws from the synchronous resource lock so that other threads waiting for the resource can get the resource and run, only if notify() is called method, the thread that called wait() before will release the wait state, and can participate in the competition for the synchronization resource lock, and then get executed. ( Note: the role of notify is equivalent to waking up a sleeping person, but not assigning tasks to him, that is to say, notify only allows the thread that called wait before to have the right to re-participate in the scheduling of the thread, and the notify method will not release it . lock, described in the example program below );

2. The sleep() method can be used anywhere; the wait() method can only be used in synchronized methods or synchronized blocks;

3. sleep() is a method of the thread class (Thread), the call will suspend the thread for the specified time, but the monitoring will remain, the object lock will not be released, and it will automatically recover when the time comes; wait() is a method of Object, and the call will Give up the object lock and enter the waiting queue. After calling notify()/notifyAll() to wake up the specified thread or all threads, it will enter the lock pool, and will not enter the running state until the object lock is obtained again;

 

Example program:

/**
 * The test program demonstrates the difference between sleep and wait methods
 * The main differences are as follows:
 * 1. These two methods come from different classes: Thread(sleep) and Object(wait);
 * 2. The most important thing is that the sleep method does not release the lock, while the wait method releases the lock, so that other threads can use the synchronization control block or method, see this program example;
 * 3. wait, notify and notifyAll can only be used in synchronous control methods or synchronous control blocks, while sleep can be used anywhere
 * @author cdzhujun
 */
public class TestSleepAndWait {
	private static class Thread1 implements Runnable{         
        @Override  
        public void run() {
            //Because the internal run method of Thread1 and Thread2 below uses the same object as a monitor, if this is used, the this of Thread1 and Thread2 is not the same object  
            //So using the bytecode object MultiThread.class, the current virtual machine refers to the same object when this variable is referenced  
            synchronized(TestSleepAndWait.class){  
                System.out.println("enter thread1 ...");  
                System.out.println("thread1 is waiting");  
                  
                try{  
                    //There are two ways to release the lock: (1) The program naturally leaves the scope of the monitor, that is, leaves the scope of the code governed by the synchronized keyword  
                    //(2) Call the wait() method of the monitor object inside the code governed by the synchronized keyword. Here the wait method is used  
                	TestSleepAndWait.class.wait();  
                }catch(InterruptedException e){  
                    e.printStackTrace ();  
                }  
                  
                System.out.println("thread1 is going on ...");  
                System.out.println("thread1 is being over!");  
            }  
        }  
          
    }  
      
    private static class Thread2 implements Runnable{  
        @Override  
        public void run() {   
            //The notify method does not release the lock, even if thread2 calls the sleep method below to rest for 6000ms, thread1 will still not execute  
            //Because thread2 does not release the lock, Thread1 cannot get the lock and cannot execute  
            synchronized(TestSleepAndWait.class){  
                System.out.println("enter thread2 ...");  
                System.out.println("thread2 notify other thread can release wait status ...");  
                TestSleepAndWait.class.notify();  
                System.out.println("thread2 is sleeping ten millisecond ...");  
                  
                try{  
                    Thread.sleep(6000);  
                }catch(InterruptedException e){  
                    e.printStackTrace ();  
                }  
                  
                System.out.println("thread2 is going on ...");  
                System.out.println("thread2 is being over!");  
            }  
        }         
    }  
      
    public static void main(String[] args) {  
        new Thread(new Thread1()).start();  
        try{  
            Thread.sleep(10);  
        }catch(InterruptedException e){  
            e.printStackTrace ();  
        }  
  
        new Thread(new Thread2()).start();  
    }  
}

 The program execution result is:

enter thread1 ...
thread1 is waiting
enter thread2 ...
thread2 notify other thread can release wait status ...
thread2 is sleeping ten millisecond ...
thread2 is going on ...
thread2 is being over!
thread1 is going on ...
thread1 is being over!

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326739044&siteId=291194637