线程Yield:

 

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

public class YieldThread 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("CostTime: " + (endTime - beginTime) + "ms");
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testYieldThread();

    }
    public static void testYieldThread(){
        YieldThread yt = new YieldThread();
        yt.start();
    }
}

运行结果:

 第一次运行结果

Java 学习笔记之 线程Yield

去掉Thread.yield();注释,再次运行,运行时间明显变长。

Java 学习笔记之 线程Yield

 

相关文章:

  • 2021-09-26
  • 2021-07-31
  • 2022-12-23
  • 2021-04-03
  • 2021-06-01
  • 2021-08-26
  • 2021-11-23
猜你喜欢
  • 2021-11-28
  • 2022-01-15
  • 2021-08-02
  • 2021-12-04
  • 2021-04-22
  • 2021-10-31
相关资源
相似解决方案