How does Thread.sleep() work when called from multiple threads

后端 未结 5 1724
暖寄归人
暖寄归人 2021-01-18 05:31

sleep() is a static method of class Thread. How does it work when called from multiple threads. and how does it figure out the current thread of execution. ?

or may

5条回答
  •  时光说笑
    2021-01-18 05:59

    Thread.sleep(long) is implemented natively in the java.lang.Thread class. Here's a part of its API doc:

     Causes the currently executing thread to sleep (temporarily cease 
     execution) for the specified number of milliseconds, subject to 
     the precision and accuracy of system timers and schedulers. The thread 
     does not lose ownership of any monitors.
    

    The sleep method sleeps the thread that called it.(Based on EJP's comments) determines the currently executing thread (which called it and cause it to sleep). Java methods can determine which thread is executing it by calling Thread.currentThread()

    Methods (static or non static) can be called from any number of threads simultaneously. Threre will not be any concurrency problems as long as your methods are thread safe. You will have problems only when multiple Threads are modifying internal state of class or instance without proper synchronization.

提交回复
热议问题