The difference between sleep() and wait() in Java

Original text: https://blog.csdn.net/u012050154/article/details/50903326

When I happened to encounter these two methods when I was studying, I consulted the relevant information and realized it through the program to make a difference:

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, notify only allows the thread that called wait before to have the right to re-participate in thread scheduling );

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;


To program description:

public class MultiThread {  

  

    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(MultiThread.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  

                    MultiThread.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 10ms, thread1 will still not execute  

            //Because thread2 does not release the lock, Thread1 cannot get the lock and cannot execute  

            synchronized(MultiThread.class){  

                System.out.println("enter thread2 ...");  

                System.out.println("thread2 notify other thread can release wait status ...");  

                MultiThread.class.notify();  

                System.out.println("thread2 is sleeping ten millisecond ...");  

                  

                try{  

                    Thread.sleep(10);  

                }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 result of running the program is shown in the following figure

640?wx_fmt=jpeg

Guess you like

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