zoukankan      html  css  js  c++  java
  • java基础---->多线程之yield(三)

      yield方法的作用是放弃当前的CPU资源,将它让给其它的任务去占用CPU执行时间。但放弃的时间不确定,有可能刚刚放弃,马上又获得CPU时间片。今天我们通过实例来学习一下yield()方法的使用。最是那一低头的温柔 像一朵水莲花不胜凉风的娇羞。

    yield方法的简单实例

    一、yield方法的简单使用

    public class YieldThread extends Thread {
        YieldThread(String string) {
            super(string);
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 10; i ++) {
                System.out.println(getName() + ", " + i);
                if (i % 2 == 0) {
                    Thread.yield();
                }
            }
        }
    }

    测试的主体类如下:

    public class YieldThreadTest {
        public static void main(String[] args) {
            YieldThread thread1 = new YieldThread("thread 1");
            YieldThread thread2 = new YieldThread("thread 2");
    
            thread1.start();
            thread2.start();
        }
    }

    一次的运行结果如下:

    thread 1, 0
    thread 2, 0
    thread 1, 1
    thread 1, 2
    thread 2, 1
    thread 2, 2
    thread 1, 3
    thread 1, 4
    thread 2, 3
    thread 2, 4
    thread 1, 5
    thread 1, 6
    thread 2, 5
    thread 2, 6
    thread 1, 7
    thread 1, 8
    thread 2, 7
    thread 2, 8
    thread 1, 9
    thread 2, 9

    从上述的结果可以看到每次i为偶数的时候,都会切换了线程。但是这种现象不能得到保证,只是一种趋势。yield的真正用途是:使当前线程从执行态变为可执行态,也就是就绪态吧。cpu会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一定会执行其他线程而该线程在下一次不会执行到了。官方文档的解释:

      A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. 
      Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect. 
      It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

    友情链接

  • 相关阅读:
    简易sql拼接工具类(使用StringBuilder实现)
    缓存工具类(使用ConcurrentMap集合实现)
    properties文档读取工具类
    【Codeforces Round #655 (Div. 2)】A-D
    【2020 杭电多校第四场】Go Running 最小点覆盖
    【2020 杭电多校第四场】1002 Blow up the Enemy
    【2020 HDU 多校训练第三场 1007 Tokitsukaze and Rescue】暴力删边&最短路
    【2020杭电多校第二场】Total Eclipse 思维+并查集
    【2020HDU多校】Lead of Wisdom 暴力
    【CF-1371 C-E2】
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusejavathreadyield.html
Copyright © 2011-2022 走看看