programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Liutauras Vilda
• Paul Clapham
Sheriffs:
• paul wheaton
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Piet Souris
Bartenders:
• Mike London

Greenhorn
Posts: 3
• Number of slices to send:
Optional 'thank-you' note:
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 ?
clip_image010_0001.jpg

author
Posts: 23931
142
• 1
• Number of slices to send:
Optional 'thank-you' note:
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.

Henry

neerav arora
Greenhorn
Posts: 3
• Number of slices to send:
Optional 'thank-you' note:
Thanks @Henry

Sheriff
Posts: 9697
43
• Number of slices to send:
Optional 'thank-you' note:
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

Ranch Hand
Posts: 531
1
• Number of slices to send:
Optional 'thank-you' note:

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 ?

Hi, Neeraj,

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.