Difference between wait() and sleep()

前端 未结 30 3882
無奈伤痛
無奈伤痛 2020-11-22 00:24

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in runni

30条回答
  •  自闭症患者
    2020-11-22 00:35

    The methods are used for different things.

    Thread.sleep(5000);   // Wait until the time has passed.
    
    Object.wait();        // Wait until some other thread tells me to wake up.
    

    Thread.sleep(n) can be interrupted, but Object.wait() must be notified. It's possible to specify the maximum time to wait: Object.wait(5000) so it would be possible to use wait to, er, sleep but then you have to bother with locks.

    Neither of the methods uses the cpu while sleeping/waiting.

    The methods are implemented using native code, using similar constructs but not in the same way.

    Look for yourself: Is the source code of native methods available? The file /src/share/vm/prims/jvm.cpp is the starting point...

提交回复
热议问题