• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multithreading  RSS feed

 
neerav arora
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
[Thumbnail for clip_image010_0001.jpg]
 
Henry Wong
author
Sheriff
Posts: 22678
113
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks @Henry
 
Ankit Garg
Sheriff
Posts: 9607
36
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anton Golovin
Ranch Hand
Posts: 531
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!