确定线程是否正在休眠

Rur*_*ano 6 java multithreading

我想知道我怎么知道一个线程是否正在睡觉.我搜索了一下,我收集了一些信息,形成了我写的一个方法 isSleeping():boolean 我认为我可以在一个类中确定线程是否正在休眠.我只是想知道我可能错过了什么.注意:我没有经验0天的经验.

//isSleeping returns true if this thread is sleeping and false otherwise.
public boolean isSleeping(){
    boolean state = false;
    StackTraceElement[] threadsStackTrace = this.getStackTrace();

    if(threadsStackTrace.length==0){
        state = false;
    }
    if(threadsStackTrace[0].getClassName().equals("java.lang.Thread")&&
            threadsStackTrace[0].getMethodName().equals("Sleep")){
        state = true;
    }
    return state;
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 0

您可以检查Thread#getState()是否有TIMED_WAITING状态。如果使用此方法,应注意确保您没有刚刚调用过Object#wait