Is there any way to ch开发者_运维百科eck if a given thread is sleeping?
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.
Here is an ugly hack to check if the other thread is sleeping (calling Thread.sleep
):
public static boolean isSleeping(Thread t) {
StackTraceElement[] ste = t.getStackTrace();
return ste.length > 0
&& ste[0].getClassName().equals("java.lang.Thread")
&& ste[0].getMethodName().equals("sleep");
}
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.
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
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.
精彩评论