Rani Karunakaran
Greenhorn
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

Nicola Garofalo
Ranch Hand
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.

Nicola Garofalo
Ranch Hand
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
Posts: 2
Oh Yes, thanks...

Campbell Ritchie
Sheriff
Posts: 50284
80
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.