In this blog, we will introduce daemon threads and thread priorities. The contents include:
- Introduction to thread priority
- Examples of thread priority
- Examples of daemon threads
Introduction to thread priority
The thread priority in java ranges from 1
to 10
, and the default priority is 5
. High-priority threads will take precedence over low-priority threads.
There are two kinds of threads in java: user threads
and daemon threads
. They can be distinguished by the isDaemon()
method: if false
is returned, the thread is a user thread
; otherwise it is a daemon thread
.
User threads
generally perform user-level tasks, while daemon threads
are also known as “ackground threads and are generally used to perform background tasks. It should be noted that the Java virtual machine will exit after all user threads
have ended.
Description from the JDK official document (https://docs.oracle.com/cd/E17802_01/j2se/j2se/1.5.0/jcp/beta1/apidiffs/java/lang/Thread.html):
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method
Examples of thread priority
1 | public class PriorityDemo { |
Results:
1 | main(5) |
The priority of the main thread
is 5
.
The priority of t1
is set to 1
, and the priority of t2
is set to 10
. When the CPU executes t1
and t2
, it is scheduled according to the time slice, so it can be executed concurrently.
Examples of daemon threads
1 | public class DaemonDemo { |
The main thread
is a user thread
, and the sub-thread t1
it creates is also a user thread
.
t2
is a daemon thread
. When the main thread
and t1
(they are both user threads
) are executed, and only the daemon thread
t2
remains, the JVM automatically exits.