Determining whether to sleep

I was wondering how I can find out if a thread was sleeping or not. I searched around and I gathered some information, forming this information, which isSleeping () method wrote : boolean , which I think I can put in a class to determine if the thread was sleeping or not. I just want to know what I might have missed. Note: I have 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; } 
+6
source share
3 answers

Change β€œSleep” β†’ β€œSleep”. In addition, you should not take stacktrace on this , your method should accept the 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 
+1
source

You can check if Thread # getState () has a TIMED_WAITING state. if you use this approach, you should ensure that you just call Object#wait .

0
source

I have this idea, I have not tested it, but I think it will work:

You can expand the flow and redefine sleep to switch state. Something like that:

  @Override public static void sleep(long millis, int nanos) throws InterruptedException { SLEEPMARKER = true; super.sleep(millis, nanos); SLEEPMARKER = false; } @Override public static void sleep(long millis) throws InterruptedException { SLEEPMARKER = true; super.sleep(millis); SLEEPMARKER = false; } 

To do this, you only need a marker and getter.

 public static boolean SLEEPMARKER = false; public static boolean isSleeping(){ return SLEEPMARKER; } 
0
source

All Articles