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

Yielding...

jolyon holdstock
Greenhorn

Joined: May 03, 2007
Posts: 3
Hi,

I have a question with regard to the code below.

Its a standard scenario of a bank account with 2 people withdrawing cash if the funds are available.
The output varies with whether the Person yields or not.

If there is no yielding then the output is as follows
a does all the withdrawing

a 0 withdrawing $20; balance is 80
a 1 withdrawing $20; balance is 60
a 2 withdrawing $20; balance is 40
a 3 withdrawing $20; balance is 20
a 4 withdrawing $20; balance is 0

If I uncomment the yielding then a does the first withdrawl, yields and then b does all the rest

a 0 withdrawing $20; balance is 80
b 0 withdrawing $20; balance is 60
b 1 withdrawing $20; balance is 40
b 2 withdrawing $20; balance is 20
b 3 withdrawing $20; balance is 0

If I uncomment the yielding line and the line that prints who is yielding then the withdrawls alternate

a 0 withdrawing $20; balance is 80
a is yielding...
b 0 withdrawing $20; balance is 60
b is yielding...
a 1 withdrawing $20; balance is 40
a is yielding...
b 1 withdrawing $20; balance is 20
b is yielding...
a 2 withdrawing $20; balance is 0
a is yielding...
b is yielding...
a is yielding...
b is yielding...

This final output is what i would have expected with yielding alone and am wondering why the addition of the print statement changes things.

Does anyone have any ideas?

thanks

j



SCJP
Vijay Jeyam
Greenhorn

Joined: Nov 12, 2008
Posts: 15
You are running a loop which runs 4 times. So the yeild statement is running 4 times.

Try adding the else block for the if(accoutbalance<20) with return or break then it may not show.


Never Never Never Give Up...!!!
jolyon holdstock
Greenhorn

Joined: May 03, 2007
Posts: 3
Hi Vijay,

Thanks for the reply.

Its not that the line is printed, its about the order that the threads are being processed.

By inserting the yield command I expected another thread chosen at random to proceed but the order of execution is always the same. So i don't understand how the yield is working; also including the print statement affects the thread chosen to proceed.

cheers,

J
Mads jacobsen
Greenhorn

Joined: Nov 20, 2008
Posts: 7
when calling yield(); you allow other threads with higher priority to be executed, if no other threads exsist with higher priority, a thread at random will be picked.
Without knowing what, i suspect that something in your code is causing the executing thread to get a higher priority then the other thread.
try adding a getPriority() call to your code, might be fun to se what the result is
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Yielding...