Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if Thread is sleeping [duplicate]

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;
}
like image 497
Ruru Morlano Avatar asked Mar 13 '13 15:03

Ruru Morlano


People also ask

How can you tell if a thread is asleep?

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.

Can sleep () method causes another thread to sleep?

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.

Why thread sleep is not recommended?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

Does thread sleep block other threads?

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.


1 Answers

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
like image 141
Evgeniy Dorofeev Avatar answered Oct 11 '22 03:10

Evgeniy Dorofeev