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

wait() and sleep() methods in Java

1. wait()

The function of the wait() method is to let the thread that acquired the lock release the lock and enter the waiting block. Therefore, the wait() method must be called only when the lock is acquired, otherwise an exception will be thrown, for example:

public class Test{
    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        test.wait();
    }
}

output:

When calling wait, you can specify how long to wait, otherwise the thread will wait indefinitely until it is woken up by the notify or notifyAll method.

The usage scenario of the wait method: The wait method is usually used to require a resource to continue executing code, and the resource is acquired and prepared by other threads. At this point you can release the lock and join the wait. Usually the structure is as follows:

synchronized(lock) {
     while(condition is not true) {
         lock.wait();
     }
    // condition is met, work
}
// another thread
synchronized(lock) {
    // Prepare resources
    lock.notifyAll();
}

Two, sleep ()

  • The sleep() method will cause the current thread to enter blocking;

  • If the current thread holds a lock, the lock will not be released when sleep enters the block;

  • The sleep method call must specify the sleep time;

  • The sleep method is a static method on Thread.

3. The difference between wait() and sleep()

  • The thread that wait enters must be awakened by the notify or notifyAll method.

  • The call of the wait method requires the current thread to acquire the lock, that is, it can only be called in the synchronized method.

  • The wait method is an instance method in Object, and sleep is a static method in Thread.

  • The wait method will cause the current thread to release the lock, and then enter the blocking wait, while sleep will not release the lock.

Supongo que te gusta

Origin blog.csdn.net/m0_57614677/article/details/129010649
Recomendado
Clasificación