This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Yield Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Question about Yield" Watch "Question about Yield" New topic
Author

Question about Yield

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hello All,

I was trying something on yield() method , and found that behavior of the program is not what I expected. I'm sure, I must have mistaken the concept of yield, and now would like to know the science behind this.



As per K&B in page 712 on threads, it says yield() method would keep the locks and would not release them.

From the above statement, I assumed that, when the first thread enters run, and have a lock on this (MyClass) object, it increments value and would keep the lock with itself without releasing it (due to yield() method). This should prevent the second thread ,entering run and have a lock on this (as already being held with first thread). So I believed that value would be incremented only once and the value would be printed 11 some time later after Main thread is awaken. But this is not what happening . Value is incremented twice and 12 is printed finally in main method.

Where did I do a mistake in understanding this concept? Please some one clarify me on this.Thanks in advance.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16695
    
  19

Where did I do a mistake in understanding this concept? Please some one clarify me on this.Thanks in advance.


Well, assuming the yield() was even honored, what do you think will happen to the thread? Yield just means to give up the current timeslice. The other thread will block because it can't get the lock, and the main thread is sleeping, which thread do you think will run again?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Oh I got it now . I thought, it was the second thread that is entering into the Run. I never realized that the first thread can again take over the control. That was so stupid of me .


Thanks Henry, for making me understand the logic behind that
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Question about Yield
 
Similar Threads
How to make yield() work as expected
Thread Behaviour? Help!!!
Concurrency Question with Thread.sleep(5000) ?
yield() on synchronized code
help regarding synchronized methods