Brief Introduction to Java Thread.yield() – Java Thread.yield()的简要介绍

最后修改: 2018年 9月 15日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll explore the method yield() in Thread class.

在本教程中,我们将探讨Thread类中的yield()方法。

We’ll compare it with other concurrency idioms available in Java and eventually explore the practical applications of it.

我们将把它与Java中可用的其他并发习性进行比较,并最终探索它的实际应用。

2. Synopsis of yield()

2.yield()的简介

As the official documentation suggests, yield() provides a mechanism to inform the “scheduler” that the current thread is willing to relinquish its current use of processor but it’d like to be scheduled back soon as possible.

正如官方文档所建议的,yield()提供了一种机制来通知 “调度器”,当前线程愿意放弃其当前使用的处理器,但它希望尽快被调度回来。

The “scheduler” is free to adhere or ignore this information and in fact, has varying behavior depending upon the operating system.

调度器 “可以自由地坚持或忽略这些信息,事实上,根据操作系统的不同有不同的行为。

The following code fragment displays two threads at same priority yielding after each schedule:

下面的代码片段显示了两个具有相同优先级的线程在每个日程安排后产生的结果。

public class ThreadYield {
    public static void main(String[] args) {
        Runnable r = () -> {
            int counter = 0;
            while (counter < 2) {
                System.out.println(Thread.currentThread()
                    .getName());
                counter++;
                Thread.yield();
            }
        };
        new Thread(r).start();
        new Thread(r).start();
    }
}

When we try to run the above program multiple times, we get different results; some of them are mentioned below:

当我们尝试多次运行上述程序时,我们会得到不同的结果;其中一些结果在下面提到。

Run 1:

运行1。

Thread-0
Thread-1
Thread-1
Thread-0

Run 2:

运转2。

Thread-0
Thread-0
Thread-1
Thread-1

So as you can see the behavior of yield() is non-deterministic and platform dependent as well.

所以你可以看到,yield()的行为是不确定的,而且也与平台有关。

3. Comparing with Other Idioms

3.与其他成语的比较

There are other constructs for affecting the relative progression of threads. They include wait(), notify() and notifyAll() as part of Object class, join() as part of Thread class, and sleep() as part of Thread class.

还有其他一些结构用于影响线程的相对进度。它们包括作为Object类一部分的wait()notify()notifyAll(),作为Thread类一部分的join(),以及作为Thread类一部分的sleep

Let’s see how do they compare to yield().

让我们看看它们与yield()相比如何。

3.1. yield() vs wait()

3.1.yield()wait()对比

  • While yield() is invoked in the context of the current thread, wait() can only be invoked on an explicitly acquired lock inside a synchronized block or method
  • Unlike yield(), it is possible for wait() to specify a minimum time period to wait before any attempt to schedule the thread again
  • With wait() it is also possible to wake the thread anytime through an invocation of notify() or notifyAll() on the concerned lock object

3.2. yield() vs sleep()

3.2.yield()sleep()对比

  • While yield() can only make a heuristic attempt to suspend the execution of the current thread with no guarantee of when will it be scheduled back, sleep() can force the scheduler to suspend the execution of the current thread for at least the mentioned time period as its parameter.

3.3. yield() vs join()

3.3.yield()join()对比

  • The current thread can invoke join() on any other thread which makes the current thread wait for the other thread to die before proceeding
  • Optionally it can mention a time period as its parameter which indicates the maximum time for which the current thread should wait before resuming

4. Usage for yield()

4.yield()的用法

As the official documentation suggests it’s rarely necessary to use yield() and hence should be avoided unless very clear with the objectives in the light of its behavior.

正如官方文档所建议的,很少有必要使用yield(),因此应该避免使用,除非根据其行为对目标非常清楚。

Nonetheless, some of use for yield() include designing concurrency control constructs, improving system responsiveness in a compute-heavy program etc.

尽管如此,yield()的一些用途包括设计并发控制结构,提高计算量大的程序中的系统响应速度等等。

However, these usages must be accompanied by detailed profiling and benchmarking to ensure the desired outcome.

然而,这些使用必须伴随着详细的剖析和基准测试,以确保预期的结果。

5. Conclusion

5.总结

In this brief article, we discussed the yield() method in the Thread class and saw its behavior and limitations through a code fragment.

在这篇简短的文章中,我们讨论了Thread类中的yield()方法,并通过一个代码片段看到了它的行为和限制。

We also explored its comparison against other concurrency idioms available in Java and finally looked upon some of the use cases where yield() might be useful.

我们还探讨了它与Java中其他可用的并发习性的比较,最后探讨了yield()可能有用的一些用例。

As always, you can check out the examples provided in this article over on GitHub.

一如既往,你可以在GitHub上查看本文提供的例子