Explain the difference between sleep () and wait () in Java

Explain the difference between sleep () and wait () in Java

For the sleep () method, we first need to know that the method belongs to the thread class. The wait () method belongs to the object class.

The sleep () method causes the program to suspend execution for the specified time and give up the CPU to other threads, but its monitoring status remains the holder. When the specified time expires, it will automatically resume running status.

During the call to the sleep () method, the thread does not release the object lock.

When the wait () method is called, the thread will give up the object lock and enter the wait lock pool waiting for this object. The thread will enter the object lock pool for preparation only after the notify () method is called for this object

Get the object lock and enter the running state.

What do you mean?

For example:

Operation effect:

If the code is commented out:

Operation effect:

And the program has been suspended.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>