If I am correct then why not any body mentioned this in Difference between wait() and sleep()
(You are correct.)
Because that is the same in both cases is not a difference. The Q & A's you have linked to ask about the differences between sleep
and wait
.
Presumably because the authors of the specific answers that you read didn't think it was relevant to what they were saying. Or because they thought it was obvious.
Also,As per my understanding when Thread.sleep(t) is called,after time t,interrupt signal is generated to consider this task also for next cpu cycle.what happens in case of object.wait()? does interrupt is also generated for object.wait()?
I presume you are talking about hardware interrupts here, because no Java interrupts are involved.
The answer is that it is way more complicated than you think. The timers that are used to terminate Java sleep
and timed wait
calls may or may not be implemented using hardware interrupts. That is OS specific. But if they are, I would expect the OS to implement them both the same way. (Because the functional requirements are pretty similar).
The broad brush implementation would be something like this:
Java makes syscall via native code. The syscall request either:
- wake me after N milliseconds, or
- wake me when notified or after N milliseconds
- The OS schedules a "wakeup" for N milliseconds time
- The OS marks the native thread as blocked
- After approximately N milliseconds, the OS timer (or whatever) unblocks the native thread; i.e. it becomes runnable
Immediately, or sometime later, the OS thread scheduler schedules it to a core and the thread runs.
- for a sleep, the Java thread just runs
- for a timed wait, the Java runtime either generates and throws an
InterruptedException
, or it tries to reacquire the mutex, etcetera. The latter may block again.
There are multiple ways that the OS could implement "wake up after N" milliseconds. Some of the strategies are:
- Use a separate hardware timer for each wakeup. This doesn't scale, since hardware times are a finite / limited resource.
- Use a single hardware timer for all wakeups. In effect, the timer is set for the earliest of future wakeups.
- Set a hardware timer to trigger once every C milliseconds, and consider wakeups at those points.
For the precise details, you will need to download and read OpenJDK source code AND the source for the OS. Also, the details are liable to be different for different versions of Java and different versions of the OS.