Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If there's only one thread running(main) and sleep(1000) is invoked, will the thread sleep for exactly 1 second or atleast 1 second?

In the below code:

 class Test {
      public static void main(String [] args) {
           printAll(args);
      }
      public static void printAll(String[] lines) {
           for(int i=0;i<lines.length;i++){
                System.out.println(lines[i]);
                Thread.currentThread().sleep(1000);
           }
      }
 }

Will each String in the array lines output:

  1. With exactly 1-second pause between lines?
  2. With at least 1-second pause between lines?
like image 975
paidedly Avatar asked Dec 06 '25 04:12

paidedly


2 Answers

Approximately 1-second pause. The thread can be woken up beforehand and you'll get an InterruptedException, or the thread can sleep for 1000ms and then not get to run immediately, so it will be 1000ms + microseconds (or more, if there are higher priority threads hogging the CPU).

You're also calling it wrong. It's Thread.sleep(1000);, as a static method it always acts on the current thread and you can't make other threads sleep with it.

like image 161
Kayaman Avatar answered Dec 10 '25 18:12

Kayaman


So it will sleep for exactly 1 second to the best of it's knowledge. The thread.sleep method is not perfect. See this and other related questions:

https://stackoverflow.com/a/18737109/4615177

like image 30
George Avatar answered Dec 10 '25 18:12

George



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!