The difference between sleep and wait

Keywords: Programming

The difference between sleep and wait

1.sleep is a Thread method, while wait is an Object method

2. The sleep method object will not release the object lock, but will suspend execution for a specified time, but the monitoring status will remain, and it will run again when the specified time is up

When the wait method is called, the thread will release the object lock and enter the waiting lock pool waiting for the object. It needs to execute the notify() method to enter the object lock pool preparation and get the object lock and enter the running state.

Example:

package com.test;

public class TestD {

    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        try {
            Thread.sleep(1000);
        }catch(Exception e){
            e.printStackTrace();
        }
        new Thread(new Thread2()).start();
    }

}
package com.test;

public class Thread1 implements Runnable{


    @Override
    public void run() {
        synchronized (TestD.class){
            System.out.println("Get into Thread1");
            System.out.println("thread1 Waiting for");
            try {
                TestD.class.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread1 is going");
            System.out.println("Thread1 is over");

        }
    }
}

 

package com.test;


public class Thread2 implements Runnable{
    @Override
    public void run() {
        synchronized (TestD.class){
            System.out.println("Get into thread2");
            System.out.println("thread2 stay sleeping");
            TestD.class.notify();
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("thread2 is going");
            System.out.println("thread2 is over");
            }
    }
}

Do not comment on the run result of the notify method:

Enter Thread1
thread1 is waiting
Enter thread2
thread2 is sleeping
thread2 is going
thread2 is over
Thread1 is going
Thread1 is over

Comment on the results of the notify method

Enter Thread1
thread1 is waiting
Enter thread2
thread2 is sleeping
thread2 is going
thread2 is over 

Explanation: after the sleep method, the notify method is annotated, and the thread is suspended.

Posted by Bac on Tue, 10 Dec 2019 20:28:20 -0800