These are a few conceptual doubts.
I read this in a book while preparing for SCJP
Just because a thread’s sleep() expires, and it wakes up, does not mean
it will return to running. It simply goes back to the runnable state.
So you can't rely on sleep() for an accurate timer.
Say I have threads t1 and t2 and an object obj1.
1) I have called sleep() for 5 seconds on t1 which was doing some work on obj1. There is still some work pending to do by t1 on obj1. sleep() does not release the lock on obj1. At the same time t2 is trying to access obj1.
But if there is no guarantee that t1 will get running again, could such a situation arise where t2 would keep on waiting forever? Could such a situation be avoided?
2) If t1 is making changes to obj1 according to its task, and in between I call wait() on t1. t2 steps in and makes changes to obj1 according to its work.
When t1 gets running again, it would be a mess, right? Because the state of obj1 then would be whatever was done by t2, and t1 would lose all the work done by it before wait() was called.
3) wait() is a non-static method, so could one thread cause another thread to wait, if it has a reference of the other thread? Is there any example to understand this kind of application?
4) Also I read something that wait() has to be called from a synchronized context, and it's a bad idea to call sleep() from a synchronized context. What is the reason for both of these?