I was wondering how I could know if a thread is sleeping or not. I searched around and I gathered some information, form those information I wrote a method isSleeping():boolean that I think I can put in a class to determine if the thread is sleeping or not. I just want to know what I might have missed. Note: I am not experienced 0 days of experience.
//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;
}
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.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.
Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.
Change "Sleep" -> "sleep". Besides you should not take stacktrace on this
, your method should accept a Thread parameter. Consider this
Thread t = new Thread(new Runnable(){
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(100);
if(t.getStackTrace()[0].getClassName().equals("java.lang.Thread")&&
t.getStackTrace()[0].getMethodName().equals("sleep")){
System.out.println("sleeping");
}
output
sleeping
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With