understanding thread priorities and daemon thread in java
In Java, threads have a priority that can be set using the setPriority() method of the Thread class. Thread priority is used by the JVM's scheduler to determine the order in which threads are executed. Higher priority threads are more likely to be executed before lower priority threads. However, it's important to note that thread priority is only a hint to the JVM's scheduler and it's up to the JVM to decide the actual scheduling order.
Thread Priority Levels
In Java, thread priorities are represented as integers between 1 and 10, where 1 is the lowest priority and 10 is the highest priority. You can set a thread's priority using the setPriority() method, passing in one of the predefined constants: MIN_PRIORITY, NORM_PRIORITY, or MAX_PRIORITY, or any integer value between 1 and 10.
Thread t = new Thread(); t.setPriority(Thread.MIN_PRIORITY);
Daemon Threads
In Java, you can also create daemon threads using the setDaemon() method. A daemon thread is a thread that runs in the background and provides services to other threads in the JVM. When all non-daemon threads have finished executing, the JVM will automatically exit, even if there are still daemon threads running. Daemon threads are typically used for tasks that need to run in the background, such as garbage collection, log file maintenance, and so on.
Thread t = new Thread(); t.setDaemon(true);
Thread Priority and Daemon Threads
When a daemon thread is created, it inherits the priority of its parent thread. If the parent thread has a high priority, the daemon thread will also have a high priority. If the parent thread has a low priority, the daemon thread will also have a low priority. However, because daemon threads run in the background, they often have lower priorities than other threads. This is because the JVM gives higher priority to user threads that are actively running and processing data.
It's also worth noting that a thread's priority and daemon status are not the same thing. A thread can be a daemon thread and have a high priority, or it can be a user thread and have a low priority. The two concepts are independent.