方法产量如何工作? [英] How does method yield work?

查看:72
本文介绍了方法产量如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javadoc中,有人说yield方法

In javadoc there is said that yield method

使当前正在执行的线程对象暂时暂停并允许其他线程执行.

Causes the currently executing thread object to temporarily pause and allow other threads to execute.

Katherine Sierra和Bert Bates的SCJP书中说

And Katherine Sierra and Bert Bates SCJP book says that

yield()应该做的是 使当前正在运行的线程回到可运行状态,以允许其他线程 轮到他们获得同样的优先权.

yield() is supposed to do is make the currently running thread head back to runnable to allow other threads of the same priority to get their turn.

那么方法实际上在做什么?

So what actually method is doing?

推荐答案

给出多线程应用程序,yield将导致当前正在执行的线程暂停执行并设置为等待状态.然后,JVM将开始运行先前处于等待状态的另一个线程.

Given a multi-threaded application, yield will cause the currently executing thread to pause execution and be set in a waiting state. The JVM will then begin running another thread that was previously in a waiting state.

我相信,从技术上讲,刚刚产生的同一线程可以安排为再次开始.

I believe the same thread that just yielded could technically be scheduled to start again.

我还没有在野外看到它.所以我认为可以避免.

And I have yet to see this in the wild though. So I think it is safe to avoid.

详细说明:

在多线程环境中,线程是根据JVM的意愿进行调度和取消调度的.因此,即使未在代码中调用yield,您的线程也可以/将在JVM决定自动将其屈服到其他线程时.这样一来,多线程便可以在只有一个处理核心的环境中工作.

In a multi-threaded environment threads are scheduled and unscheduled off and on at the JVM's will. So, even if yield is not called in code, your thread can/will automatically yield to other threads when the JVM decides it should. This allows multi-threading to work in an environment with only one processing core.

调用yield只是告诉JVM即使JVM不想将当前线程置于等待状态.

Calling yield simply tells the JVM to put the current thread in a waiting state even if the JVM wasn't going to.

我将尝试说明:
下面是一个非常简单的说明,说明了随着时间的推移(假设有1个核心)执行2个线程的情况-

I shall attempt an illustration:
The following is a very simplified illustration of the execution of 2 threads over time (assume 1 core)-

Thread\Time    1    2    3    4    5    6    7    8    9
Thread 1    -----------       -----          -------
Thread 2               -------     ----------       ------

每当您看到'-'表示线程正在执行时. ' '表示线程正在等待.如您所见,一次实际上只能运行1个线程.因此,当1运行时,另一个在等待.产生的结果是让其他线程有机会在当前运行的线程之前运行.

Whenever you see a '-' that means a thread is executing. A ' ' means that the thread is waiting. As you can see, only 1 thread can actually run at a time. So, while 1 runs, the other waits. What yield is intended to do is give other threads a chance to run ahead of the currently running thread.

这篇关于方法产量如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆