Think of it this way... Two people (let's say you and me) decided to write "A", "B", and "C" on the same sheet of paper. Then we have to read that paper.
So, you will write "A", "B", "C", and then you will read what you wrote. Additionally, you will also read what I wrote so far. I will do the same, I will read what I wrote, plus I will read what you wrote so far.
Depending on the ordering, it should be possible to see 3 or 4 of each letter. Although, based on the timing of the threads, I would speculate that it would favor 3 rather than 4.
To add to what Henry said, you might see different number of repetitions of each letter. If I were to represent the execution of both threads simultaneously, you'll see how this is possible
In the above example, A is printed 4 times but B and C are printed 3 times each. This is a very simple example, you might get confusing results if both threads are executing the for loop at the same time [Edit: I miss the part that the printAll method is synchronized so this can't happen]. You can add the thread name to the output to understand it better
neerav arora wrote:Could anyone please help me in Question number 20 at the following link webpage . How can there be more than two A's,B's,C's in the output ?
Any one thread will always write at most up to 2 As, 2 Bs, and 2Cs; however, there are two of them, so you may get up to 4 As, 4 Bs, and 4 Cs in some weakly determined order but i would surmise always starting with an A?
With best regards,
Anton Golovin (email@example.com) SCJP, SCJD, SCBCD, SCWCD, OCEJWSD, SCEA/OCMJEA [JEE certs from Sun/Oracle]
It's a pleasure to see superheros taking such an interest in science. And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop