Search code examples
javamultithreadingrunnablethread-sleep

Difference between Thread.sleep() and Object.sleep()


I have a function:

Thread myThread = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
                myThread.sleep(500);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
        }
    }
});

Is calling Thread.sleep(500); the same as calling myThread.sleep(500);?

Are there any differences between the two different calls?


Solution

  • public static void sleep(long millis)
                  throws InterruptedException
    

    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 is static. It should always be called as Thread.sleep(). Writing otherThread.sleep() does not cause otherThread to sleep; it causes the current thread to sleep.