if Thread.sleep is static, how does individual thread knows it is put to sleep?

前端 未结 2 1836
走了就别回头了
走了就别回头了 2021-01-17 22:25

I am a bit confused with Thread.sleep() method. if Thread.sleep() is a static method, how does two threads know which is put to sleep. For example,

相关标签:
2条回答
  • 2021-01-17 22:48

    Does it mean Thread.sleep() puts the current Thread to sleep?

    Yes. Only the current thread can do that.

    What if t1 wants to put t to sleep. that shouldn't be possible correct?

    Right. You can set a volatile boolean flag that will cause another thread to call Thread.sleep(...) but another thread can't cause a thread to sleep.

     volatile boolean shouldSleep = false;
     ...
     // check this flag that might be set by another thread to see if I should sleep
     if (shouldSleep) {
         Thread.sleep(...);
     }
    
    0 讨论(0)
  • 2021-01-17 22:49

    It can find the current thread from Thread.currentThread(). The current thread only can put itself to sleep.

    0 讨论(0)
提交回复
热议问题