เธรด daemon มักใช้เพื่อดำเนินการบริการสำหรับเธรดผู้ใช้ วิธีการ main() ของเธรดแอปพลิเคชันคือ เธรดผู้ใช้ (เธรดที่ไม่ใช่ daemon) . JVM ไม่ยุติเว้นแต่ เธรดผู้ใช้ (ไม่ใช่ภูต) . ทั้งหมด สิ้นสุด เราสามารถระบุเธรดที่สร้างโดย เธรดผู้ใช้ . ได้อย่างชัดเจน เพื่อเป็นเธรด 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