What is the result of attempting to compile and run the program?
a. Prints: T1T1T1 b. Prints: T1T1T2 c. Prints: T1T2T2 d. Prints: T1T2T3 e. Prints: T1T1T3 f. Prints: T1T3T3 g. Compile-time error h. Run-time error i. None of the above
wht is the answer to this q and y? this is a dan's q...however, the explanation is unclear.
[ October 25, 2004: Message edited by: Barry Gaunt ]
Barry, you are very right in asking what did happen when you try to compile and run, but it is not the question, the problem is how did this result arrives.
JayaSiji, first compile and run the code and if the answer doesn't match with your answer, then try to find out what is the reason behind this answer.
This question is pretty simple, but you need to put some efforts in to this before understanding the complete concept.
Sometimes, Kap, it's a Good Thing to hold back a little until the questioner has shown the initiative to do something themselves. Theoretical Physics I can understand, but not Theoretical Programming.
This is both what I expected, and what it did. Note however I wasn't so confident that I posted my response without trying it!
Anyway, why?
We create a new thread (new B(), "T1") which is called T1.
The run method is invoked (on a new stack) with the start call. This new stack, called T1, immediately creates an A and calls run. It does not create a thread, it just calls run, so there is no new stack frame. It is not a new thread, and prints out the current thread name T1.
Next, we create a new thread A, but again we do not call start. We call the run method on the thread. From the sun docs:
run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
So this calls the run method of A- which prints out T1- there is no new stack frame for T2. If you change it to a start() call you get T1T2T3, but since we didn't, we get T1.
Finally, we call the new thread correctly, and create a thread which gets its own stack frame with the start() call. When the run method is executed now it finds the new name of the thread T3.
Yes, Barry, you are right!!! Till the time questioner shows interest in solving the question, there is no use in answering it because he will not be able to understand the solution without working on it himself.
If you change it to a start() call you get T1T2T3, but since we didn't, we get T1.
Calling start() on T2 does not necessarily cause T1T2T3 to print. You cannot be certain which thread is going to be executed first. The OS controls that. You could just as easily get T1T3T2
Post by:autobot
Mo-om! You're embarassing me! Can you just read a tiny ad like a normal person?
a bit of art, as a gift, that will fit in a stocking