Q41. What is the difference between sleep() and wait() method, with regards to lock?

Ans:  When thread calls sleep(), method it is not necessary to have it in synchronized block. However, if you are in synchronized block and you call sleep() method on thread. It will not release the lock. And also note that sleep is a Thread class method and not a part of “Common object”.

Q42. What is the difference between sleep() , join() and yield() method of Thread class?

Ans : sleep() : causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.

Q43. What do you mean by missed signals?

Ans: It is possible that a thread can miss a signal. Let’s assume there are two threads ThreadA and ThreadB. ThreadA is going to enter in wait() state and ThreadB is going to notify(). However, ThreadB notify() ThreadA before ThreadA enter in wait() block. In this case notify() signal from ThreadB is missed by ThreadA. Hence, ThreadA remain in wait state forever, which could be a big problem. Missed signal problem can be avoided using proper code block around shared object.

Q44. What is a spurious wakeup?

Ans: It is possible because of any surprise reason like hardware issue, thread gets signal. Lets assume again we have two threads ThreadA and ThreadB , ThreadA is waiting on notification from ThreadB. However, ThreadA gets notification that ThreadB has done with its processing. This is a false signal and known as a spurious wakeup of ThreadA.

To avoid spurious wakeup issue, we should check wait state of shared object in while loop. So in case of false signal it has to check condition on shared object again.

Q45. When should notifyAll() used?

Ans : notifyAll() should be used when many threads are waiting for signal.