Java basics - the difference between sleep and wait

This article introduces the difference between the sleep and wait methods in Java

sleep()

Looking at the sleep method, it can be seen that it is a static native method

public static native void sleep(long millis) throws InterruptedException;

The sleep() method needs to be specified 等待的时间.

It allows the currently executing thread to suspend execution within a specified time and enter a blocked state. This method can not only allow other threads of the same priority or high priority to be executed, but also allow low-priority threads to be executed. Chance.

But the sleep() method 不会释放“锁标志”, that is to say, if there is a synchronized synchronization block, other threads still cannot access the shared data.

wait()

public final native void wait(long timeout) throws InterruptedException;

The wait() method will release the "lock flag" of the object.
When the wait() method of an object is called, the execution of the current thread will be suspended, and the current thread will be put into the object waiting pool until the notify() method is called, it will be removed from the object waiting pool and 任意一个线程put 锁标志等待池in , only the threads in the lock mark waiting pool can acquire the lock mark, and they are ready to compete for the ownership of the lock at any time.

When the notifyAll() method of an object is called, all threads in the object waiting pool will be moved to the object's lock flag waiting pool.
insert image description here
notify() can only guarantee that the condition is satisfied at the notification time point. The execution time of the notified thread will basically not coincide with the notification time, so when the thread executes, it is likely that the condition has not been met (if it is not guaranteed, other threads will jump in the queue).
尽量使用 notifyAll()

notify() will 随机地通知wait for a thread in the queue, and notifyAll() will notify the thread in the waiting queue 所有线程. In terms of feeling, notify() should be better, because even if all threads are notified, only one thread can enter the critical section.

But the so-called feeling often has risks. In fact, using notify() is also very risky. Its risk is that some threads may never be notified.

Sleep() and wait() comparison

the difference

The difference between wait and sleep is:

  1. wait会释放所有锁,而sleep不会释放锁资源.
  2. wait只能在同步方法和同步块中使用,而sleep任何地方都可以.
  3. sleep is a static method of Thread, and wait is a method of Object, which can be called by any object instance.

Same point

Both have the same point: both will be transferred CPU执行时间, waiting to be dispatched again!

Guess you like

Origin blog.csdn.net/baidu_33256174/article/details/130715574