How does method yield work?

2019-03-27 14:08发布

In javadoc there is said that yield method

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

And Katherine Sierra and Bert Bates SCJP book says that

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?

6条回答
唯我独甜
2楼-- · 2019-03-27 14:15

yield() is generally used when you are waiting on a thread for something to occur but don't want to block the CPC cycles with something like while(condition){ ...} . The way yield() works differ from platform to platform and depends on the Thread Scheduler and you shouldn't rely on it behaving in a particular way.

查看更多
Summer. ? 凉城
3楼-- · 2019-03-27 14:15

Ultimately, the call to yield() results in calling os methods like this, which in principle would put the task itself back in to the run queue and let the next task run (source):

 /**
  * sys_sched_yield - yield the current processor to other threads.
  *
  * This function yields the current CPU to other tasks. If there are no
  * other threads running on this CPU then this function will return.
  */
 SYSCALL_DEFINE0(sched_yield)
 {
        /*
         *  lock this runqueue and disable interrupts.
         */
         struct rq *rq = this_rq_lock();

         schedstat_inc(rq, yld_count);
         current->sched_class->yield_task(rq);

         /*
          * Since we are going to call schedule() anyway, there's
          * no need to preempt or enable interrupts:
          */
         __release(rq->lock);
         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
         _raw_spin_unlock(&rq->lock);
         preempt_enable_no_resched();

         schedule();

         return 0;
 }
查看更多
乱世女痞
4楼-- · 2019-03-27 14:19

It originates from the time of cooperative multitasking. The basic idea is, the processor executes only one thread until:

  1. this thread ends
  2. this thread does some blocking operation, like object.wait() or Thread.sleep, waiting on some IO operation to complete, waiting for some object monitor, or similar.
  3. this thread invokes Thread.yield().

In each of this cases the thread scheduler then selects another thread to execute. So, to be fair to other threads, you would in longer loops without any blocking operations regularly call yield(). (If no other thread is ready to run, then the same thread would be scheduled again, so no really big performance loss.)

In modern VMs thread switching can occur on any point, not only these listed, threads may even be executed simultaneously, so it is not really necessary, and some VMs may ignore it altogether (similar to System.gc().)

查看更多
ら.Afraid
5楼-- · 2019-03-27 14:23

Threads may be in states ready (runnable), blocked (e.g., waiting for some io to finish), or running; this is common to all thread implementations, although some particular implementations may have more states.

Yield causes the thread to change from running to runnable, and wait for the scheduler to change it to running again, in the future. This is what is meant in the SCJP book.

To the thread, it seems like it has been paused for a while, like described in the javadoc. So both statements are correct, just differently phrased.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-03-27 14:25

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.

To elaborate:

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.

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

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               -------     ----------       ------

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.

查看更多
\"骚年 ilove
7楼-- · 2019-03-27 14:36

yield() method is there to make sure that all same priority threads in a application would not cause starvation. For e.g. five threads are there in a application and all of them are of same priority. Now suppose one thread got chance to run and this thread is taking so long to complete its task and hence other threads wont get chance to run. So to avoid this kind of situations yield() is there to rescue.

查看更多
登录 后发表回答