Multithreading in Java allows for concurrent execution of multiple threads
within a single program. One important concept in multithreading is the daemon
thread.
In Java, a daemon thread is a special type of thread that provides services to
user threads. Its existence is dependent on the user threads; once all user
threads are terminated, the JVM automatically terminates the daemon thread as
well.
Several Java daemon threads, such as the finalizer and gc, run automatically in the
background.
In simple words, a daemon thread is there to support and assist user threads with
tasks running in the background. Apart from serving user threads, it doesn't have
any specific purpose.
Multithreading in Java brings the capability of running multiple threads simultaneously, and the concept of daemon threads helps in managing and supporting these user threads efficiently.
public final boolean isDaemon()
public final void setDaemon(boolean on)
import java.io.*; public class Main extends Thread{ public void run(){ if(Thread.currentThread().isDaemon()){ //checking for daemon thread System.out.println("Daemon thread work"); } else{ System.out.println("User thread work"); } } public static void main(String[] args){ Main thread1=new Main();//creating thread Main thread2=new Main(); Main thread3=new Main(); thread1.setDaemon(true);//now t1 is daemon thread thread1.start();//starting threads thread2.start(); thread3.start(); } }
Output:
Daemon thread work
User thread work
User thread work
public class Main extends Thread{ public void run(){ System.out.println("Current Thread Name: "+Thread.currentThread().getName()); System.out.println("Daemon Thread: "+Thread.currentThread().isDaemon()); } public static void main(String[] args){ Main thread1=new Main();//creating thread Main thread2=new Main(); thread1.start();//starting threads thread1.setDaemon(true);//now t1 is daemon thread thread2.start(); } }
Output:
Current Thread Name: Thread-0
Exception in thread "main" Daemon Thread: false
java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.setDaemon(Thread.java:1403)
at HELLO/DockerTpoint.Main.main(Main.java:15)
Police Colony
Patna, Bihar
India
Email:
Post your comment