深入剖析Thread.yield()

本文通过两个具体示例介绍了 Java 中 Thread.yield() 方法的作用及使用方式。该方法提示线程调度器当前线程愿意暂停执行,让相同或更高优先级的线程有机会运行。文章展示了 yield() 方法如何影响主线程与高优先级子线程之间的执行顺序。

  • Whenever a thread calls java.lang.Thread.yield method, it gives hint to the thread scheduler that it is ready to pause its execution. Thread scheduler is free to ignore this hint.
  • If any thread executes yield method , thread scheduler checks if there is any thread with same or high priority than this thread. If processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give processor to other thread and if not – current thread will keep executing.


场景一:

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++)
            System.out.println(Thread.currentThread().getName()
                    + " in control");
    }
}

// Driver Class
public class YieldDemo {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();

        for (int i = 0; i < 5; i++) {
//            Thread.yield();

            System.out.println(Thread.currentThread().getName()
                    + " in control");
        }
    }
}

输出 :

main in control
main in control
main in control
main in control
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control

Thread-0 in control

结果输出并不唯一,但基本主线程先结束。

场景二:

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++)
            System.out.println(Thread.currentThread().getName()
                    + " in control");
    }
}

// Driver Class
public class YieldDemo {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();

        for (int i = 0; i < 5; i++) {
            Thread.yield();

            System.out.println(Thread.currentThread().getName()
                    + " in control");
        }
    }
}

去掉Thread.yield()注释。输出:

main in control
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
main in control
main in control

main in control


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值