Hi, Can some one explain the odd behaviour in threads. I thought that calling start method two times should throw IllegalThreadStateException. How ever the following code compiles fine and executes fine. Another interesting point I observed is the run method is called only once.
Hi Sarma, I think that the reason why the exception error did not occur is because the start method has already returned (the thread is already dead). Try removing the t.join method and replace it with t.start(); Hope this helps, Maria
What I noticed is that it doesn't need to be a join but any method that ensures a delay long enough to let the started thread finish (sleep or wait). I guess Maria has got a point. The exeption did not occur because the thread was already dead. Although I've seen stated that the exeption should occur if one calls start on a dead thread it looks like the exception only occurs if one calls start on a live thread. The following code have the same behavior as the previous ones and run is called only once. If you comment the sleep line you'll get the error.
It has been my experience that an IllegalThreadStateException is NOT thrown if the start method is invoked on a dead thread. However, the exception is thrown if the thread is still running when the start method is invoked. For the purposes of the exam it is important to know that the javadoc for the Thread class states that the IllegalThreadStateException is thrown if the start method is invoked on a thread that has already been started. The exam does not test your knowledge of undocumented behavior. Anytime there is a conflict between your practical experience and the documented behavior of Java then you should answer based on the documented behavior and not your actual experience. Your practical experience tells you that an IllegalThreadStateException is not thrown when the start method is invoked on a dead thread, but the documentation tells you that an exception is thrown when the start method is invoked on a thread that has already been started. If your exam contains a question where the start method is invoked on a thread more than once, then the correct answer will involve the IllegalThreadStateException. Remember, the exam prefers documentation over actual experience. The reasoning is that undocumented behavior can disappear at anytime so you should not write your code based on the assumption that undocumented behavior will become a defacto standard.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>