• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Behavior of yield() in Threads

 
Komal Amaresh
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Sir,

I have tried the following code and I'am confused with respect to the yield() method.



The yield() method whether placed after the statement in the loop or in the main() is giving almost the same output. Can you please explain the right place to use the yield() method.

Thanks in advance

with regards
komal
 
Komal Amaresh
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sir,

I' am sorry for sending the same question again. i thought i had closed without sending. Please ignore it

With regards,
komal
 
Campbell Ritchie
Sheriff
Pie
Posts: 49808
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have deleted your duplication. This question is too difficult for beginners. Moving.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yield doesn't do much of anything, really, nowadays; it offers other threads at the same priority a chance to run. Since virtually all modern thread libraries do round-robin time-sliced execution anyway -- i.e., every thread of a given priority automatically gets a chance to run. yield() was much more important when Java was new and most implementations were using a thread library (Green threads) that did not do time slicing -- i.e., without a call to yield(), the running thread might never give up the CPU.
 
Ryan Beckett
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you called Thread.currentThread().yield() in the main method than it will go in the waiting stage, and one of the three threads (maybe due to time slicing) will go to the running stage. If you called it in run() then the currently executing thread that implements Runnable will wait.

Here we go:

I got this output using the code you got:


Thread2 .....started
Hello Thread2
Thread1 .....started
Hello Thread1
Hello Thread2
Hello Thread1
Thread3 .....started
Hello Thread3
Hello Thread2
Hello Thread1
Hello Thread3
Thread2 ....stopped
Thread1 ....stopped
Hello Thread3
Thread3 ....stopped


Thread 2 started before Thread 1 this time. The code you have says that's likely to happen. But, if you comment out Thread.currentThread().yield() in main, you'll never ever get that because the first thread starts and maybe it doesn't print at first (due to context switching) but directly after (while no other threads are runnable) main goes back into a running state and then gives controls back (yield()) to a runnable thread. The one runnable thread in the pool is the first one.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic