As the question suggests , I want to know the similarity between the sleep and join methods on the thread. I have gone through many questions that describe the difference betwee
NO NO NO
sleep
and join
are completely different.
join
will wait for the specified Thread
to finish (either normally or abnormally) or until the time expires.
sleep
will simply stop the current thread for the specified time.
They are completely different. One explicitly waits for another Thread
and wakes the instant that that Thread
ends. sleep
just stops execution.
If you can guarantee than newThread
will take longer then 10,000ms
to to complete then they become equivalent, but this is a degenerate case.
If you want to wait for another Thread
to complete use join
.
If you want your current Thread
to stop what it's doing and sleep for a while use sleep
.
It's not clear to me what your actual question is, but your third sentence in says, "I would like to know different scenarios where the sleep and join methods could be used interchangeably."
From a practical point of view, if you worked with a team of software developers writing production code, there would be no scenarios in which other developers would permit you to use join(long) as an alternative to sleep(long). No way, no how! It does not matter that there are circumstances under which it would actually work.
Production code should be readable. The intent of the code should be obvious to others. It should obey The Principle of Least Surprise (See Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin). That means, when you write foobar.join(n), you should be expecting the foobar thread to die. You might be prepared to handle the timeout case, but that should be the exception, not the rule. There is no other legitimate reason to call join(n). Anything else would be a "hack", and we do not put hacks in production code.