Author Topic:   threads
kris
unregistered
posted March 16, 2000 11:11 PM           
i have found this question in one of the mock exam.
would u plz clarify this question.

which of the following statements about the Object::wait() is true

a. A wait method should be enclosed in try/catch block handling interrupted exception.

b. when a running thread executes a wait statement the running thread is paused and another thread starts.The paused thread will resume execution when the other thread finishes.

c. A wait method must be enclosed in a synchronized block or an InterruptedExeption will be thrown.

d. If the current thread doesnot have the object's monitor before executing a wait statement the InterruptedException will be thrown.


the answer given was "a".
i feel that it must be "b" also.


maha anna
bartender
posted March 17, 2000 12:14 AM             
Kris,
when a running thread executes a wait statement the running thread is paused and another thread starts.The paused thread will resume execution when the other thread finishes.

The first half is true. The second half is not true. The second half may ot may not happen. Here is my thoughts.

There are 3 types of wait. wait() / wait(long timeout) / wait(long timeout,int nanosec). When any version of this wait method is invoked on an object it MUST be enclosed in a try ..catch..InterruptedException block because at any time it may be interrupted by another thread by calling interrupt on this thread or by calling notify() / notifyAll() . When a thread calls wait(), it goes to the waiting state giving away all of its locks, well not all exactly all of them , it unlocks only this current object and if the thread has locked any other objects before, those objects will still remain locked by this thread.Also note that at any time , a thread can have more than 1 lock corresponing to more than 1 object.When this waiting thread is in the waiting state there are many ways to come out of this waiting. The 2nd and 3rd versions of wait which take a time for its arg, comes out of this waiting when the time elapses. Or if it is interrupted by another thread (by interrupt() /notify() / notifyAll() )before this timeout also it comes out of this waiting. After waiting is over it goes directly to Ready state The 1st version of wait (wait()) waits , until another thread notifies this thread by calling notify() / notifyAll().
In order to call wait(..) / notify() / notifyAll() , the thread MUST first obtain the object's lock first. Obtaining lock is done througn the synchronized keyword. Otherwise no compile error will occur. But at run time IllegalMOnitorStateException will occur.

So after waiting is over the waited thread goes to ReadyState is true. But there is no gurantee that this will be the next one to run. It is upto the thread scheduling mechanism to decide which is the next to run.

regds
maha anna

[This message has been edited by maha anna (edited March 17, 2000).]

|