How to check if a thread is sleeping?

岁酱吖の 提交于 2019-12-09 02:51:32

问题


Is there any way to check if a given thread is sleeping?


回答1:


You can call Thread.getState() on and check if the state is TIMED_WAITING.

Note, however that TIMED_WAITING doesn't necessarily mean that the thread called sleep(), it could also be waiting in a Object.wait(long) call or something similar.




回答2:


Here is an fairly ugly hack to check if the other thread is sleeping:

public static boolean isSleeping(Thread t) {
    StackTraceElement[] ste = t.getStackTrace();

    if (ste.length == 0)
        return false;     // thread has terminated!

    return ste[0].getClassName().equals("java.lang.Thread")
        && ste[0].getMethodName().equals("sleep");
}



回答3:


I am not sure if there is a better way but you could change a variable when a thread goes to sleep and check that variable if the thread is sleeping or not.




回答4:


You could create your own sleep method which records the Thread's ID to a global variable and use it as reference for sleeping thread.

There's no other way you can tell if a thread is precisely sleeping.

Hope the three links below help:

  • States
  • Java Doc 1
  • Java Doc 2



回答5:


i didn't actually did it , but there's an ThreadMXBean Interface for getting thread Info

which returns ThreadInfo Class, there you might get something with getWaitedTime method.



来源:https://stackoverflow.com/questions/5336299/how-to-check-if-a-thread-is-sleeping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!