按照惯例先吟诗一首:
杂诗
唐代:王维
君自故乡来,应知故乡事。
来日绮窗前,寒梅著花未?
yield()方法的作用是让当前线程放弃当前cup资源,让其他任务获取cup资源。但放弃的时间不确定,有可能放放弃又马上获取cpu资源。
基本使用
下面用代码来说明:
MyThread类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class MyThread03 extends Thread{ @Override public void run() { long beginTime=System.currentTimeMillis(); int count=0; for (int i=0;i<50000000;i++){ // Thread.yield(); count=count+(i+1); } long endTime=System.currentTimeMillis(); System.out.println("用时="+(endTime-beginTime)+"毫秒"); } }
|
YieldTest类
1 2 3 4 5 6 7
| public class YieldTest { public static void main(String[] args){ MyThread03 thread03=new MyThread03(); thread03.start(); } }
|
结果如下:
用时=23毫秒
将MyThread03类更改一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class MyThread03 extends Thread{ @Override public void run() { long beginTime=System.currentTimeMillis(); int count=0; for (int i=0;i<50000000;i++){ Thread.yield(); count=count+(i+1); } long endTime=System.currentTimeMillis(); System.out.println("用时="+(endTime-beginTime)+"毫秒"); } }
|
结果如下:
用时=10552毫秒
最后更新时间:
这里可以写作者留言,标签和 hexo 中所有变量及辅助函数等均可调用,示例:
http://suxianglun.github.io/2017/06/01/Java线程常用方法之yield()/