yield方法的作用是房企当前的CPU资源,将他让给其他的任务去占用CPU执行时间,但房企的时间不确定,有可能刚刚放弃,马上又获得CPU时间片。
package yield; /** * Created by liping.sang on 2017/1/13 0013. */ public class Mythread extends Thread{ public void run(){ long beginTime = System.currentTimeMillis(); int count = 0 ; for(int i=0;i<500000;i++){ count = count+(i+1); } long endTime = System.currentTimeMillis(); System.out.println("用时:"+(endTime-beginTime)+"毫秒!"); } }
package yield; /** * Created by liping.sang on 2017/1/13 0013. */ public class Run { public static void main(String [] args){ Mythread thread = new Mythread(); thread.start(); } }
用时:16毫秒!
如果加入Thread.yield()则结果变为:
用时:130毫秒!