This blog will introduce the yield()
method in Thread
. The content involved includes:
- Introduction to
yield()
yield()
example- Comparison of
yield()
andwait()
Introduction to yield()
The effect of yield()
is to give in. It can make the current thread enter the runnable state
from the running state
, so that other waiting threads with the same priority can obtain execution rights. However, there is no guarantee that after the current thread calls yield()
, others have the same priority will be able to obtain the execution right. It may also be that the current thread enters the running state
and continues to run!
yield() example
1 | public class YieldDemo { |
One of the possible result:
1 | t1 [5]:0 |
t1
did not switch to t2
when it could be divided by 4. This shows that although yield()
can make the thread enter the runnable state
from the running state
, it does not necessarily allow other threads to obtain CPU execution rights (that is, other threads enter the running state
), even if other threads have the same priority as the thread currently calling yield()
.
Comparison of yield() and wait()
We know that wait()
will let the current thread enter the blocked state (wait)
from the running state
, and also release the synchronization lock. yield()
will also make the current thread leave the running state
. The difference is:
wait()
will let the thread enter theblocked state (wait)
from therunning state
, whileyield()
will let the thread enter therunnable state
from therunning state
.wait()
will release the synchronization lock of the object it holds, and theyield()
method will not release the lock.yield() will give up the CPU execution time, rather than giving up the resource lock
1 | public class YieldDemo2 { |
Results:
1 | t1 [5]:0 |
The main thread started two threads t1
and t2
. t1
and t2
will reference the synchronization lock of the same object in run()
, namely synchronized(obj)
. While t1
is running, although it will call Thread.yield()
, t2
will not get cpu execution rights. Because, t1
did not release the synchronous lock of obj
!