class Tt implements  Runnable{
int i=0;
public void run(){
while(true){
System.out.println("num is :"+ i++);
try{
Thread.sleep(5);
}
catch(InterruptedException e){
;
}
if(i == 100)
Thread.yield();
}
}
}public class Test{
public static void main(String[] args ){
Tt r = new Tt();
Thread t = new Thread(r);
t.start();
//r.run();
while(true){
System.out.println("love is good!!!!!");
}
}
}
源代码如上,感觉那个yield没有起作用,怎么整的?

解决方案 »

  1.   

    yield只是暂时让出,让其它线程进行
      

  2.   

    那有什么函数可以停止线程呢?stop已经过时,是否用intterupt??
      

  3.   

    线程退出可以使用标记法,定义一个私有的标记变量。如下(只写部分方法)private boolean stop=false;public void exit()
    {
        this.stop=true;
    }public void run()
    {
        while(!stop){
            //do something
        }
    }另外yield方法只是让当前线程交出CPU的运行权给与它具有同一优先级的其他线程,如果没有则该方法是不被执行的!
      

  4.   

    现在线程退出我知道的方法只有标记一种,用已经drprecated的方法是有危险的,感觉这个跟操作系统安排指令流有关系,自己标记,可以更好的控制.