1.9yield方法

yield()方法的作用放弃当前的cpu资源,将他让给其他的任务去占用cpu的执行时间,但放弃的时间不确定,有可能刚放弃,马上又获得cpu时间片

测试

 1 package com.cky.thread;
 2 
 3 /**
 4  * Created by edison on 2017/12/3.
 5  */
 6 public class MyThread3 extends Thread{
 7     @Override
 8     public void run() {
 9         super.run();
10         long begin = System.currentTimeMillis();
11         int count =0;
12         for (int i = 0; i < 5000000; i++) {
13             //Thread.yield();
14             count=count+(i+1);
15         }
16         long end = System.currentTimeMillis();
17         System.out.println("用时" +(end-begin)+"毫秒");
18     }
19 }
 1 package com.cky.test;
 2 
 3 import com.cky.thread.MyThread3;
 4 
 5 /**
 6  * Created by edison on 2017/12/3.
 7  */
 8 public class Test3 {
 9     public static void main(String[] args) {
10         MyThread3 th = new MyThread3();
11         th.start();
12     }
13 }
package com.cky.thread;

/**
 * Created by edison on 2017/12/3.
 */
public class MyThread3 extends Thread{
    @Override
    public void run() {
        super.run();
        long begin = System.currentTimeMillis();
        int count =0;
        for (int i = 0; i < 5000000; i++) {
            Thread.yield();
            count=count+(i+1);
        }
        long end = System.currentTimeMillis();
        System.out.println("用时" +(end-begin)+"毫秒");
    }
}

上述两种情况运行结果

有注释:48毫秒

无注释:11100毫秒

结果说明了他放弃当前的cpu资源。

原文地址:https://www.cnblogs.com/edison20161121/p/7954792.html