Ganish Patil wrote:Is this the way we should use wait and notify? If yes then if possible how can I improve it or If not please anyone help me to figure it out.
Arguably, the main purpose of wait & notify is to wait for the *exact* amount of time -- meaning it is waiting for a period of time, exactly when the other thread is ready. It is a little bit more complex than that, but anyway... If you don't wait the exact period of time, then there are two possible issues. Waiting too little will eat up CPU cycles, as the thread is constantly waking up, only to find that the other thread is not ready. Waiting too much will waste time, as there will be periods where the thread is waiting when the other thread is already done.
So, question one. What is the purpose of all those sleep() calls in your code? Are you trying to guess the amount of waiting time? Isn't that what the wait() call is for? The advantage of waiting the exact amount of time is moot here, as your code goes and sleeps some more time.
Question two. Why is the waiting only in one direction? Your reader waits for the writer, which notifies when data is ready. This is fine. But what about the other direction? Shouldn't the writer wait until the reader is done reading too? And the reader can notify the writer that it can write?
Additionally, you have some issues related to lost notifications -- which is technically a bug. However, it is hidden by all those sleep() calls, so you probably won't encounter them, until you try to get rid of the sleep() calls.
Henry