Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
MarsPeople Avatar asked Feb 19 '26 15:02

MarsPeople


1 Answers

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.

like image 170
John Kugelman Avatar answered Feb 22 '26 04:02

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!