aspose file tools*
The moose likes Beginning Java and the fly likes Confusing Multithreaded output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusing Multithreaded output" Watch "Confusing Multithreaded output" New topic
Author

Confusing Multithreaded output

Rani Karunakaran
Greenhorn

Joined: Jun 02, 2010
Posts: 2
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

Joined: Apr 10, 2010
Posts: 308
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.

Bye,
Nicola
Nicola Garofalo
Ranch Hand

Joined: Apr 10, 2010
Posts: 308
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

Joined: Jun 02, 2010
Posts: 2
Oh Yes, thanks...
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusing Multithreaded output