14. Thread.yield()

Thread.yield() 是 Java 中 Thread 类的一个静态方法,用于提示线程调度器当前线程愿意让出 CPU 资源,以便其他具有相同或更高优先级的线程有机会运行。不过,yield() 并不保证当前线程一定会暂停,具体行为取决于操作系统的线程调度策略。

1. yield() 的作用

  • 提示调度器yield() 向线程调度器发出信号,表示当前线程愿意让出 CPU 资源。
  • 不保证暂停:调用 yield() 后,当前线程可能会继续运行,也可能被暂停,具体取决于调度器的实现。
  • 不释放锁yield() 不会释放当前线程持有的锁。

2. 使用场景

  • 协作式多任务处理:在需要多个线程协作完成任务时,yield() 可以让其他线程有机会运行。
  • 性能优化:在某些情况下,使用 yield() 可以减少线程竞争,提升整体性能。

3. 示例代码

public class YieldExample implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " is running - " + i);
            if (i == 2) {
                System.out.println(Thread.currentThread().getName() + " is yielding");
                Thread.yield(); // 提示调度器当前线程愿意让出 CPU
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new YieldExample(), "Thread-1");
        Thread t2 = new Thread(new YieldExample(), "Thread-2");

        t1.start();
        t2.start();
    }
}

4. 输出示例

Thread-1 is running - 0
Thread-2 is running - 0
Thread-1 is running - 1
Thread-2 is running - 1
Thread-1 is running - 2
Thread-1 is yielding
Thread-2 is running - 2
Thread-2 is yielding
Thread-1 is running - 3
Thread-2 is running - 3
Thread-1 is running - 4
Thread-2 is running - 4

5. 注意事项

  • 不可靠yield() 的行为依赖于操作系统和 JVM 的实现,不能保证线程一定会暂停。
  • 不替代同步机制yield() 不能替代 wait()notify()join() 等线程同步机制
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值