Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing Multithreaded output

 
Rani Karunakaran
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand, that little is guaranteed where multithreading is concerned. But i am not able to understand the output which i am getting for the below program.
acc is a shared object by these threads...
output:
Fred is going to withdraw. Current balance :50
Lucy is going to withdraw. Current balance :50
Lucy completes withdrawal, now Current balance :30
Lucy is going to withdraw. Current balance :30
Lucy completes withdrawal, now Current balance :10
Lucy is going to withdraw. Current balance :10
Lucy completes withdrawal, now Current balance :-10
Fred completes withdrawal, now Current balance :30 why is it 30 and not -30???
Fred is going to withdraw. Current balance :30
Fred completes withdrawal, now Current balance :10
Fred is going to withdraw. Current balance :10
Fred completes withdrawal, now Current balance :-10

Please help.
 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hallo Rani,
you make a loop of 3 iterations, starting from 50, subtracting 20 everytime for each thread.
How could you expect a -30?

If you start from 50

first iteration 50 - 20 = 30

second iteration 30 - 20 = 10

third iteration 10 - 20 = -10

That's all.

You put to sleep thread named Fred for 2 seconds before the loop begins, so Lucy probably will be the first to complete method run. So it happens that while Fred is sleeping,Lucy complete her loop starting from 50 (30,10,-10) , then it's Fred's turn.
 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry Rani, i forgot to clear this.

When you write



you create two instances of class ThreadSynch1, each instance has its own Account instance.
You are not sharing the Account, you have two copies of it, two separate objects.
 
Rani Karunakaran
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh Yes, thanks...
 
Campbell Ritchie
Sheriff
Pie
Posts: 48981
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Please always use the code button for code. I shall try and edit your first post so you can see how much better it looks.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic