yield() The function of the method is to give up the current CPU resources , Give it up to other tasks to occupy CPU execution time . When the time of giving up is uncertain , Maybe just gave up , Get it right away CPU Time slice .
In the operating system , Threads can prioritize , Higher priority threads get CPU More resources , That is to say CPU Priority execution of tasks in higher priority thread objects .
stay Java in , The priority of threads is divided into 1~10 this 10 Level , If it is less than 1 Or greater than 10, be JDK Throw an exception throw new IllegalArgumentException().
JDK Use in 3 Constant to preset the priority value , The code is as follows ：
public final static int MIN_PRIORITY = 1; public final static int NORM_PRIORITY = 5; public final static int MAX_PRIORITY = 10;
stay Java in , The priority of a thread is inherited , such as A Thread start B Threads , be B Priority of thread and A It's the same .
High priority threads always execute most of them first , But it doesn't mean that all high priority threads execute first .
When thread priority levels vary greatly , Who executes first has nothing to do with the calling order of the code .
The priority of thread has certain regularity , That is to say CPU Try to give execution resources to threads with higher priority .
If the priority of the thread is higher, the execution of run() Task in method , But the result can't be said for sure , Because the priority of threads also has “ Randomness ”, That is to say, the higher priority thread does not have to execute every time .
Don't measure the priority of threads against the order in which they run results , Higher priority threads do not necessarily complete each execution first run() Task in method , in other words , Thread priority has nothing to do with print order , Don't associate the two . Their relationship is uncertain and random .
stay Java There are two kinds of threads , One is the user thread , The other is guarding （Daemon） Threads .
What is a guardian thread ？
Daemons are special threads , Its characteristics have the meaning of companionship , When there are no non daemons in the process , Then the daemons automatically destroy . A typical daemon thread is a garbage collection thread , When there are no non - daemons in the process , Then there is no need for the garbage collection thread to exist , Automatically destroy .
Use a popular metaphor to explain “ The guardian thread ”： Any one of the daemons is the whole JVM Of all non - daemons in “ nanny ”, As long as the present JVM Any non daemonic thread in the instance is not ended , The daemons are working , Only when the last non - daemonic thread ends , The daemonic thread follows JVM Finish the work together .Daemon Its function is to provide convenient services for other threads , The most typical application of daemons is GC ( Garbage collector ), It is a very competent guardian .