CodeGym/Java Course/Module 2. Java Core/yield (surrendering the right of way)

yield (surrendering the right of way)

Available

"Hello, Amigo! Today we will have a short but interesting lesson. I'm going to tell you about yield, a static method of the Thread class."

Ellie has already told you that the processor constantly switches between threads. Each thread is allocated a small piece of processor time, called a quantum. When this time expires, the processor switches to another thread and starts executing its commands. Calling Thread.yield() lets you end the current thread's quantum early. In other words, it tells the processor to switch to the next thread.

"But why would one thread need to give up its time to another thread?"

"It doesn't happen often. Calling yield means «our thread is done with its turn ahead of schedule» and that the command after the yield will start with a full time quantum. Thus, the chances that it will be interrupted are less. Especially if it's a short command, i.e. it won't take long to execute. This approach can be used to optimize some processes."

I can also tell you that Thread.sleep(0) actually works the same way. I think you won't use the yield method very much at first, but it's useful to know about.

Comments (7)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
remote87
Level 18 , Sofia, Bulgaria
22 March 2021, 17:05
Noooo, my 17 darkmatter....
Johannes
Level 27 , Centurion, Pretoria, South-Africa
3 April 2020, 12:59
Does this mean that the processor would sit and wait out the quantum, if "yield" is not specified, and the work for the particular thread was completed ahead of time ?
Daniel Walbolt
Level 22 , Waterville, United States
14 July 2020, 16:59
Well sitting and waiting is relative to the speed of the processor lol. The thread's quantum is switched within milliseconds.
shabarish kumar
Level 20 , Hyderabad, India
6 January 2020, 10:52
can we say yield functionality is opposite to join functionality!
Aldo Luna Bueno
Level 28 , Peru
17 March 2022, 02:56
Actually, no. The opposite of the yield method would be a method that prevents the processor from switching to another thread, i.e. keeping the current thread running. The join and yield methods share the same characteristic: they both allow the processor to execute other threads other than the current one. The sleep method does the same thing, which is why it can be a substitute for the yield method.
Daniel Tinsley
Level 22 , United States, United States
11 November 2019, 20:33
That's different from yield in Python, since it's used for generators in Python, not for multithreading.
28 August 2019, 22:26
will try to remember about it