“This is the 16th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Both sleep and wait methods are used to put a thread into sleep state, and both sleep and wait methods can respond to interrupts while the thread is sleeping. InterruptedException is thrown. What is the difference between sleep and Wait? Next, let’s see.

Difference 1: Different grammar usage

Wait method must be used with synchronized together, otherwise will be thrown at runtime exception IllegalMonitorStateException, as shown in the following code:At first glance, the code appears to be fine, and the compiler does not report any errors. However, when we run the above program, the following error occurs: Sleep can be used alone without synchronization.

Difference 2: Different classes

Wait methods belong to the Object class, while sleep methods belong to the Thread class, as shown below:

Difference three: different ways to wake up

The sleep method must pass a timeout, after which the thread will wake up automatically. The wait method does not pass any parameters. If it does not pass any parameters, it is permanently dormant. The dormant thread cannot be awakened until another thread calls notify or notifyAll. That is to say, the sleep method has an active wakeup function, while the wait method, which passes no parameters, can only be woken up passively.

Difference 4: Different lock release resources

The wait method actively releases the lock, while the sleep method does not. Let’s use code to demonstrate the difference.

Sleep does not release locks

Next, use sleep to sleep the thread for 2s, and then try to acquire the common lock in another thread. If sleep can obtain the lock, then it will release the lock, otherwise it will not release the lock.

public static void main(String[] args) throws InterruptedException {
    Object lock = new Object();
    new Thread(() -> {
        synchronized (lock) {
            System.out.println(New thread acquires lock: + LocalDateTime.now());
            try {
                / / sleep 2 s
                Thread.sleep(2000);
                System.out.println("New thread gets lock released:" + LocalDateTime.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
    // wait for the new line to acquire the lock first
    Thread.sleep(200);
    System.out.println("Main thread attempts to acquire lock:" + LocalDateTime.now());
    // Try to acquire the lock after the new thread sleeps
    synchronized (lock) {
        System.out.println("The main thread got the lock:"+ LocalDateTime.now()); }}Copy the code

The execution result of the above code is shown below:As can be seen from the above results, after sleep was called, the main thread tried to acquire the lock but failed. Only after sleep was executed, the lock was released, and the main thread could get the lock normally. This indicates that sleep does not release the lock during sleep.

Wait to release the lock

Use the same method to replace sleep with wait, and try to acquire the lock in another thread after sleep.

public static void main(String[] args) throws InterruptedException {
    Object lock = new Object();
    new Thread(() -> {
        synchronized (lock) {
            System.out.println(New thread acquires lock: + LocalDateTime.now());
            try {
                / / sleep 2 s
                lock.wait(2000);
                System.out.println("New thread gets lock released:" + LocalDateTime.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
    // wait for the new line to acquire the lock first
    Thread.sleep(200);
    System.out.println("Main thread attempts to acquire lock:" + LocalDateTime.now());
    // Try to acquire the lock after the new thread sleeps
    synchronized (lock) {
        System.out.println("The main thread got the lock:"+ LocalDateTime.now()); }}Copy the code

The execution result of the above code is shown below:As can be seen from the above results,When wait is called, the main thread attempts to acquire the lock immediately, indicating that the lock is released when wait sleeps.

Difference 5: Different thread entry states

Call the sleep method and the thread will enter the TIMED_WAITING timed state. Call the wait method with no parameters and the thread will enter the WAITING timed state. Code demo:

public static void main(String[] args) throws InterruptedException {
    Object lock = new Object();
    Thread t1 = new Thread(() -> {
        synchronized (lock) {
            try {
                / / sleep 2 s
                lock.wait();
            } catch(InterruptedException e) { e.printStackTrace(); }}}); t1.start(); Thread t2 =new Thread(() -> {
        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) { e.printStackTrace(); }}); t2.start(); Thread.sleep(200);
    System.out.println("Wait () to enter the state:" + t1.getState());
    System.out.println("Into state after sleep(2000) :" + t2.getState());

}
Copy the code

The result of the above code is as follows:

conclusion

Sleep and wait can both put threads to sleep and respond to interrupts, but they differ in syntax, class, wake up, lock release, and state entry.

Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.

Public number: Java interview analysis

Interview collection: gitee.com/mydb/interv…