Java Reference
In-Depth Information
Listing 6-16. Setting and Getting a Thread's Priority
// ThreadPriority.java
package com.jdojo.threads;
public class ThreadPriority {
public static void main(String[] args) {
// Get the reference of the current thread
Thread t = Thread.currentThread();
System.out.println("main Thread Priority:" + t.getPriority());
// Thread t1 gets the same priority as the main thread at this point
Thread t1 = new Thread();
System.out.println("Thread(t1) Priority:" + t1.getPriority());
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("main Thread Priority:" + t.getPriority());
// Thread t2 gets the same priority as main thread at this point, which is
// Thread.MAX_PRIORITY (10)
Thread t2 = new Thread();
System.out.println("Thread(t2) Priority:" + t2.getPriority());
// Change thread t2 priority to minimum
t2.setPriority(Thread.MIN_PRIORITY);
System.out.println("Thread(t2) Priority:" + t2.getPriority());
}
}
main Thread Priority:5
Thread(t1) Priority:5
main Thread Priority:10
Thread(t2) Priority:10
Thread(t2) Priority:1
Is It a Demon or a Daemon?
A thread can be a daemon thread or a user thread. The word “daemon” is pronounced the same as “demon.” However,
the word daemon in a thread's context has nothing to do with a demon!
A daemon thread is a kind of a service provider thread, whereas a user thread (or non-daemon thread) is a thread
that uses the services of daemon threads. A service provider should not exist if there is no service consumer. The JVM
applies this logic. When it detects that all threads in an application are only daemon threads, it exits the application.
Note that if there are only daemon threads in an application, the JVM does not wait for those daemon threads to finish
before exiting the application.
You can make a thread a daemon thread by using the setDaemon() method by passing true as its argument.
You must call the setDaemon() method of a thread before you start the thread. Otherwise, an java.lang.
IllegalThreadStateException is thrown. You can use the isDaemon() method to check if a thread is a daemon
thread.
 
Search WWH ::




Custom Search