Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of yield() ???

Nasir Khan
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.awt.*;
import java.awt.event.*;
class mythread extends Frame implements Runnable,ActionListener {
int x=0,y=0,x1=0,x2=0,x3=0;String nm;boolean flag=true;
public void run(){
for ( int c=0;c<800 ;c++ ) call();
Button bt=new Button("Start");
public void update(Graphics g ){ g.drawString("|",x,y);
public void paint(Graphics g){update(g);}

public static void main(String[]au){

mythread mt=new mythread();
public void actionPerformed(ActionEvent ae){ Thread t1=new Thread(this,"1");
Thread t2=new Thread(this,"2");
Thread t3=new Thread(this,"3");
t3.setPriority(10);//even i kept all priorities same //can't see any differece
//using yield as below
t3.start(); }

synchronized void call(){
while ( flag )
try { wait();
catch(InterruptedException ie){}
String nm=Thread.currentThread().getName();
int sw=Integer.parseInt(nm);
case 1 :{ x1++ ; y=40;x=x1;// no change when used //Thread.yield();here
break; }
case 2 :{ x2++; y=60; x=x2;
break; }
case 3 :{ x3++; y=80;x=x3;
flag=true; repaint();
try{Thread.sleep(1); }
catch(InterruptedException ie){}
synchronized void realease(){
Threads only yeild the cpu to other threads of same priority.Right?
with above codes I can't see a useful use of yield method.
can someone suggest me a use of it so that it gets clear in my mind.also tell me if I used anything wrongly specially synchronized and wait/notify metods.
Jim Kilthau
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nasir, I did a little checking around on this and it looks like the answer is not clear cut. At the Sun site, the Java Tutorial seems to contradict itself by making these three statements:
"Only when that thread stops, yields, or becomes not runnable for some reason will a lower priority thread start executing."
"The yield method gives other threads of the same priority a chance to run. If there are no equal priority threads that are runnable, then the yield is ignored."
"Rule of thumb: At any given time, the highest priority thread is running. However, this is not guaranteed. The thread scheduler may choose to run a lower priority thread to avoid starvation."
The document states three times that the yield() will be ignored if there is not an equal priority thread in a runnable state, so I assume that this is the case and that your assumption is correct. It does seem that the scheduler can opt to give time to a lower-priority thread, when it deems necessary so's not to "starve" the other thread. I think this all depends on the version and configuration of the scheduler though.
Have fun
Clear as mud, huh?
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic