Thanks,
Pooja Oza
Pooja Oza wrote:Can some one help me understand the output of the following programs ..... The examples are from SCJP 6 by K&B book, in the self test of multithreading chapter...
The Dudes question:
You run the thread with two newly created DudesChat instances. But that's not the point as the run() method only refers to the d variable which is exactly the same for both threads.
As it is the same, the synchronized keyword in fragment I works as expected, the output will always be "yo yo dude dude" which appears in none of the possible answers.
With fragment two you have a typical unsynchronized case i.e. both methods could theoretically be entered and run at the same time. So F is at least possible.
The exam authors claim that "yo" must always be the first output although I think that it is theoretically possible that one thread sets the flag variable and immediately after that the other thread starts and completes the chat method so that "dude dude" is printed first. Any ideas if this might be possible?
The Chicks question:
You create two threads, each with a *new* instance of the ChicksYack In this new instance the c variable (which is not static as the d in the above example!) was never initialised so if the thread scheduler calls the run() method of these new instances you get a NullPointerException when it tries to call the method .yack(...) on the uninitialized variable c.
The Chess question:
Here, too, you start two threads with different instances of a class. So whether or not you put synchronized before a method is irrelevant as they both only lock their instance.
The output is thus random for both examples. As there are only two threads there can never the case where three different id values are printed so option D is invalid.
Hope that helps!
Thanks,
Pooja Oza
SCJP 88% | SCWCD 84%
------------------------
Bob
SCJP - 86% - June 11, 2009
Thanks,
Pooja Oza
neha chaukar wrote:In the dudes example also, two threads are started with different instances of class i.e.
new Thread(new DudesChat()).start();
new Thread(new DudesChat()).start();
so here also synchronised should not play any role as in chess example.
Help me understand this.
Consider Paul's rocket mass heater. |