डेमन थ्रेड्स आमतौर पर उपयोगकर्ता थ्रेड के लिए सेवाएं करने के लिए उपयोग किया जाता है। मुख्य () विधि एप्लिकेशन थ्रेड का एक उपयोगकर्ता थ्रेड (गैर-डिमन थ्रेड) . है . JVM तब तक समाप्त नहीं होता जब तक कि सभी उपयोगकर्ता थ्रेड (गैर-डिमन) समाप्त। हम स्पष्ट रूप से एक उपयोगकर्ता थ्रेड . द्वारा बनाए गए थ्रेड को निर्दिष्ट कर सकते हैं setDaemon(true) . को कॉल करके डेमन थ्रेड बनने के लिए . 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