"Hi, Amigo!"

"Now I'll tell you a little about the sleep, yield, and join methods."

"That's boring. I just found an interview question: 'What's the difference between the yield(), sleep(), and wait() methods?'. Can you explain that?"

"No problem. First off, these are three completely different methods."

1) sleep(timeout) – stops the current thread (on which sleep was called) for the number of milliseconds indicated by the timeout parameter. The thread then goes into the TIMED_WAITING state. The method may end earlier if the isInterrupted flag is set.

Example Description
The current thread suspends its own execution for 500 milliseconds, or 0.5 seconds.

2) yield() – the current thread 'skips its turn'. The thread goes from the running state to the ready state, and the JVM proceeds to the next thread. The running and ready states are sub-states of the RUNNABLE state.

Example Description
The current thread "skips its turn" and Java immediately switches to the next thread.

3) wait(timeout) – this is a version of the wait() method, but with a timeout. "The wait method can only be called within a synchronized block on a mutex object locked by the current thread. Otherwise, the method throws an IllegalMonitorStateException.

"Calling this method causes the mutex object's lock to be released, making it available for another thread to acquire. Moreover, the thread enters the WAITING state (for the wait() method without parameters) or the TIMED_WAITING state (for the wait(timeout) method)."

Example Description
Object monitor = getMonitor();
When the wait method is called, the current thread releases the monitor object's lock, and sleeps for 500 milliseconds. The monitor object can be acquired by another thread.
After 500 milliseconds, the thread will wake up and if the monitor is not busy, the thread will acquire it and continue working.
If the monitor is locked by another thread, the current thread will switch to the BLOCKED state.

4) join(timeout)

"This method wasn't in your question, but it's in my lesson plan, so I'll tell you about it. When you call the join() or join(timeout) method, the current thread is 'attached' to the Thread which called this method. The current thread goes to sleep and waits till the thread it is joined to finishes (i.e. the thread whose join() method was called)."

"The current thread enters the WAITING state for the join() method and the TIMED_WAITING state for the join(timeout) method."

Example Description
Thread thread = getWorkThread();
The current thread will join the workerThread thread and wait for it to end.
But it will 'unjoin' after 500 milliseconds and continue running.

"The timeout in the wait(timeout) and join(timeout) methods means that the method goes to sleep and waits for something, but no longer than the timeout given in milliseconds. Then it wakes up."

"It seems like the only thing these methods have in common is timeout. They do completely different things."

"Yep, that's right."