读书人

线程中的yield()方法?该如何解决

发布时间: 2012-03-21 13:33:15 作者: rapoo

线程中的yield()方法????
public class Thread4 extends Thread{

public Thread4() {
}
public void run(){
for(int i=1;i<=10;i++){
System.out.println(getName()+":"+i);
yield(); //x1
try{
sleep(1000);
}catch(InterruptedException ie){}
}
}
public static void main(String[] args) {
Thread4 t1=new Thread4();
Thread4 t2=new Thread4();
t1.start();
t2.start();
}

}
通过几次运行以上程序发现 yield()有无好象对程序的执行结果和效率没什么影响.
我知道 yield()方法使当前运行的线程对象退出运行状态,使其他线程得以运行.
请高手指点一下有无yield()方法的区别在哪里???谢谢了


[解决办法]
yield方法是暂停当前进程,然后线程调度程序从线程池里面再选一个线程出来运行.
哪一个线程会被选中是不确定的,所以这并不保证刚暂停的线程不会再次被选出来运行.
[解决办法]
线程在执行到yield()后就会让步,然后另外的线程就会执行
建议你这样就可以看到区别了
public class Thread4 extends Thread{

public Thread4() {
}
public void run(){
for(int i=1;i <=10;i++){
System.out.println(getName()+":"+i+"前");
yield(); //x1
System.out.println(getName()+":"+i+"中");
try{
sleep(1000);
}catch(InterruptedException ie){}
System.out.println(getName()+":"+i+"后");
}
}
public static void main(String[] args) {
Thread4 t1=new Thread4();
Thread4 t2=new Thread4();
t1.start();
t2.start();
}

}

[解决办法]
我说下我的理解吧
yeild只是让出CPU,避免贪婪线程抢占CPU
但是yeild之后就不能保证其执行顺序了..跟sleep一样
[解决办法]
yield会放弃该线程所占的资源,sleep会继续持有CPU等资源,这就是根本的不同

读书人网 >J2SE开发

热点推荐