Hi all, Please help in understanding the following. Thanks in advance ! One of the questions in the threads chapter in Mughal and Rasmussen's "Programmer's Guide to Java Certification" is this : Given the following program, which statements are guaranteed to be true ?
The question asked for two correct answers (a) The letter A is always printed (b) The letter B is always printed (c) The letter A is never printed after End (d) The letter B is never printed after End (e) The program might print B,End and A, in that order Their answers were (a) and (e). The explanation they gave was :
Because the exact behaviour of the scheduler is undefined, the text A,B and End can be printed in any order. The thread printing B is a daemon thread, which means that the program may terminate before the thread manages to print the letter
Here is my confusion - they say that a daemon thread "...is stopped if there are no more user threads running...". Therefore, relating this to their explanation above, the thread printing B might not get to execute if both the main thread and the thread printing A terminate. And, if this could happen, what makes (a) one of the correct answers - how can we gurantee that the thread printing A will get to execute and print A before it is terminated ? I can understand that there might be a better chance for A to be printed out of a non-daemon thread, but it seems to me that this is not what the question asked for. Am I missing something ?
Joined: Jul 27, 2001
can understand that there might be a better chance for A to be printed out of a non-daemon thread, but it seems to me that this is not what the question asked for A is a non-daemon thread and start() will definately be called before main() terminates, so the JVM cannot halt until it finishes execution. Similarly, I can execute the following code without worrying that the thread will not run because main terminates between the call to start() and when the thread actually begins to execute:
Joined: Dec 28, 2003
Thanks for your reply, David. I now realize that I took the wording of the question too literally - the intention of the question was to recognize guaranteed behavious under normal operation of the JVM. I was thinking along the lines of : what if there is some event in the JVM that halts execution of all threads period ? how then can we really guarrantee the execution of thread A ? etc.