Thread.yeild方法详解

从原理上讲其实Thread.yeild方法其实只是给线程调度机制一个暗示:我的任务处理的差不多了,可以让给相同优先级的线程CPU资源了;不过确实只是一个暗示,没有任何机制保证它的建议将被采纳;

看一个例子就知道了;

复制代码
public class LiftOff implements Runnable {

    protected int countDown = 5;

    private static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {

    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        // System.out.println(Thread.currentThread().getName());
        return Thread.currentThread().getName() + "#" + id + "(" + (countDown > 0 ? countDown + ")" : "Liftoff!" + ")");
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        /*
         * --countDown:先减去,再赋值
         * countDown--先赋值,再减去
         */
        while (countDown-- > 0) {
            System.out.println(status());
            Thread.yield();// 让步【表示我的任务处理的差不多了,可以让步给其他线程资源了】;CPU资源给其他线程使用;t.join当前线程挂起,直到t线程调用结束后切回
            /*
             * try {
             * TimeUnit.MILLISECONDS.sleep(100);
             * } catch (InterruptedException e) {
             * // TODO Auto-generated catch block
             * // e.printStackTrace();
             * System.err.println("异常终止...");
             * }
             */

        }

    }
View Code
复制代码
复制代码
public class ExecuteMethodPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();// 无界队列:将为每个任务创建一个线程
        // ExecutorService executorService = Executors.newFixedThreadPool(2);// 有限线程数队列
        // ExecutorService executorService = Executors.newSingleThreadExecutor();// 有限线程数队列

        for (int i = 0; i < 3; i++) {

            executorService.execute(new LiftOff());
        }
        executorService.shutdown();

    }

}
复制代码

响应结果打印:

 

pool-1-thread-2#1(4)

pool-1-thread-1#0(4)

pool-1-thread-3#2(4)

pool-1-thread-2#1(3)

pool-1-thread-3#2(3)

pool-1-thread-3#2(2)

pool-1-thread-1#0(3)

pool-1-thread-2#1(2)

pool-1-thread-3#2(1)

pool-1-thread-1#0(2)

pool-1-thread-2#1(1)

pool-1-thread-3#2(Liftoff!)

pool-1-thread-1#0(1)

pool-1-thread-2#1(Liftoff!)

pool-1-thread-1#0(Liftoff!)

 以上标注的两个一样的线程先后执行 并没有遵守yeild给线程调度的建议

posted @   陶朱公Boy  阅读(1252)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示