Question
Threads have the following 6 states: new, running, blocked, waiting, timed waiting and terminated.
When new a new thread is created, the thread is in the newly created state.
When the start() method is called, the thread is in a running state.
When a thread needs to obtain the object's built-in lock, and the lock is owned by another thread, the thread is blocked.
When a thread is waiting for other threads to notify the scheduler that the scheduler can run, the thread is in a waiting state.
For some methods that contain time parameters, such as the sleep() method of the Thread class, the thread can be placed in a timing waiting state.
When the run() method finishes running or an exception occurs, the thread is in a terminated state.
Implementation: View the running status of the thread.
Create a class: ThreadState, implement the Runnable interface
Define 3 methods:
waitForASecond (): Make the current thread wait for 0.5 seconds or other threads call notify() or notifyAll() method
waitForYears(): Make the current thread wait forever until other threads call notify() Or notifyAll() method
notifyNow(): wake up the thread that entered the waiting state by calling the wait() method
Use getState of the Thread class () method to obtain the status of the thread.
The return value of this method is Tread.State
package com.xiaoxuzhu; /** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre class="brush:php;toolbar:false"> * 修改记录: * 修改后版本 修改人 修改日期 修改内容 * 2022/5/10.1 xiaoxuzhu 2022/5/10 Create *
Test class:
package com.xiaoxuzhu; /** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre class="brush:php;toolbar:false"> * 修改记录: * 修改后版本 修改人 修改日期 修改内容 * 2022/5/10.1 xiaoxuzhu 2022/5/10 Create *
The above is the detailed content of How to check thread running status in Java. For more information, please follow other related articles on the PHP Chinese website!