Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a sleeping thread continue its execution in Java?

Let's say I have 2 threads a and b running inside the same process. The processor runs a few instructions from a, a few from b and so on until it reaches a line of code like this: Thread.sleep(1000).

The problem is that I don't really understand what the processor will do next. I suspect these 2 scenerios:

1)

  • Thread a starts to sleep for 1000 miliseconds
  • meanwhile b is running
  • the 1000 milisecond interval is over so:
    • if the proccessor still runs code from Thread b
      • then wait until it finishes
      • and run more code from Thread a
    • else
      • run more code from Thread a

2)

  • Thread a starts to sleep for 1000 miliseconds
  • meanwhile b is running
  • the 1000 milisecond interval is over so:

    • if the proccessor still runs code from Thread b

      • STOP THREAD B. since Thread a has higher priority and it's code must be run IMMEDIATELY after the 1000 miliseconds interval it's finished
      • and run more code from Thread a
      • THEN run code from Thread B from where we left.
    • else
      • run more code from Thread a

Which one resembles what's actually going on behind the scenes? If both are wrong then please indicate me the correct answer.

like image 560
Dragos C. Avatar asked Feb 14 '26 00:02

Dragos C.


1 Answers

A lot of factors come into play, so it's tough to provide an absolute answer for your question.

But based on the available options you have given, #2 will be closest.

A different thread is invoked to run in case one of the following events occur:

....
A thread with a higher priority than the thread currently running enters the Runnable state. The lower priority thread is preempted and the higher priority thread is scheduled to run.

Here's the source.

like image 89
Jops Avatar answered Feb 15 '26 13:02

Jops