Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How do java sleep and wait understand

Shulou Source: shulou.com Published: 2022-06-01 04:47:20 09月26日 Update

This article mainly explains "how to understand java sleep and wait". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand java sleep and wait".

Sleep lets the thread end from [running]-> [blocking state] time / interrupt-> [runnable]

Wait lets threads from [running]-> [waiting queue] notify-> [lock pool]-> [runnable]

First, remember the difference: "sleep is a method of the Thread class, and wait is a method defined in the Object class." Although both methods affect the execution behavior of threads, they are essentially different.

Thread.sleep does not cause a change in lock behavior, and Thread.sleep does not let the thread release the lock if the current thread owns the lock. If it helps you remember, you can simply assume that the lock-related methods are defined in the Object class, so calling Thread.sleep does not affect the lock-related behavior.

Both Thread.sleep and Object.wait pause the current thread, and for CPU resources, no matter how the thread is paused, it no longer needs CPU execution time for the time being. OS allocates execution time to other threads. The difference is that after calling wait, you need another thread to execute notify/notifyAll to regain the CPU execution time.

The state of the thread refers to the definition of Thread.State. The newly created thread that has not been executed (which has not yet called start ()) is in the "ready", or Thread.State.NEW state.

Thread.State.BLOCKED means that when a thread is acquiring a lock, it is forced to suspend execution of the following instruction because the lock cannot be acquired until the lock is released by another thread. For a thread in BLOCKED state, the OS scheduling mechanism needs to decide which thread can acquire the lock next. In this case, it is a lock contention, which is a time-consuming operation anyway.

Thank you for your reading, the above is the content of "how to understand java sleep and wait". After the study of this article, I believe you have a deeper understanding of how to understand java sleep and wait, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Thread method time state behavior learning content that is situation influence blocking anyway two differences ideas instructions articles ways more essence Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Apple Shulou Tech Info macOS OPPO Reno