Các daemon thread thường dùng để thực hiện dịch vụ cho user thread. Phương thức main() của ứng dụng là một user thread (non-daemon thread). JVM không kết thúc trừ khi tất cả user thread (non-daemon) kết thúc. Chúng ta có thể chỉ định rõ ràng một thread do user thread tạo thành daemon thread bằng cách gọi setDaemon(true). Để xác định thread có phải daemon không, dùng phương thức isDaemon().
Ví dụ
public class UserDaemonThreadTest extends Thread {
public static void main(String args[]) {
System.out.println("Thread name is : " + Thread.currentThread().getName());
// Kiểm tra main thread là daemon hay user
System.out.println("Is main thread daemon ? : " + Thread.currentThread().isDaemon());
UserDaemonThreadTest t1 = new UserDaemonThreadTest();
UserDaemonThreadTest t2 = new UserDaemonThreadTest();
// Chuyển t1 (user thread) thành daemon thread
t1.setDaemon(true);
t1.start();
t2.start();
}
public void run() {
// Kiểm tra thread là daemon hay không
if (Thread.currentThread().isDaemon()) {
System.out.println(Thread.currentThread().getName() + " is a Daemon Thread");
} else {
System.out.println(Thread.currentThread().getName() + " is an User Thread");
}
}
}
Kết quả
Thread name is : main Is main thread daemon ? : false Thread-0 is a Daemon Thread Thread-1 is an User Thread