7

How can I access Thread object that is executing given Runnable? What I'd like to do is to call sleep() from within run() method.

alex
  • 10,900
  • 15
  • 70
  • 100
  • 1
    Sleep is static, there is no way to *sleep* an arbitrary thread... unless you own the OS stack. – bestsss Aug 13 '12 at 14:38

2 Answers2

22

If you need to sleep within a Runnable, you can simply call Thread.sleep(); inside the run method.

To access the thread that is running the Runnable, you can call Thread.currentThread(), but that is not necessary to call the sleep method, which is static.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • yes, I should have guessed it'd be so trivial. Thanks for help anyway. – alex Aug 13 '12 at 14:46
  • Not necessary is too generous. It's not legal since you can not call sleep on a thread instance through a thread reference. You can only sleep your current thread through the static Thread.sleep(); – RichieHH Aug 07 '14 at 21:41
  • Well technically you can but it will still sleep the current thread. – assylias Aug 07 '14 at 22:39
7

you can always get the current Thread that your code is executing within by calling the static method Thread.currentThread().

But in your case, you don't need the thread itself because sleeping is controlled with the following static method:

Thread.sleep(1000L);
fommil
  • 5,757
  • 8
  • 41
  • 81