Daemon threads ใช้ทำงานเบื้องหลังสำหรับ user threads เมธอด main() ของแอปพลิเคชันเป็น user thread (non-daemon) JVM จะไม่จบการทำงานจนกว่า user threads ทั้งหมดจะจบ เราสามารถกำหนดเธรดที่สร้างโดย user thread ให้เป็น daemon ได้โดยเรียก setDaemon(true) ตรวจสอบว่าเป็น daemon หรือไม่ด้วย isDaemon()
ตัวอย่าง
public class UserDaemonThreadTest extends Thread {
public static void main(String args[]) {
System.out.println("Thread name is : " + Thread.currentThread().getName());
// Check whether the main thread is daemon or user thread
System.out.println("Is main thread daemon ? : " + Thread.currentThread().isDaemon());
UserDaemonThreadTest t1 = new UserDaemonThreadTest();
UserDaemonThreadTest t2 = new UserDaemonThreadTest();
// Converting t1(user thread) to a daemon thread
t1.setDaemon(true);
t1.start();
t2.start();
}
public void run() {
// Checking threads are daemon or not
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");
}
}
}
ผลลัพธ์
Thread name is : main Is main thread daemon ? : false Thread-0 is a Daemon Thread Thread-1 is an User Thread