Java has two types of threads first is User Thread and second is Daemon Thread.A user thread will run its own independently of other threads.Daemon thread is subordinate to a user thread means a daemon thread will automatically terminate when no more user thread are running.
class mythread extends Thread
{
private int threadnum;
mythread(int n)
{
threadnum=n;
}
public void run()
{
for(int i=0;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
System.out.println("Thread number "+ threadnum + " is running");
}
}
}
public class daemonthread
{
public static void main(String aa[])
{
System.out.println("Main thread start");
mythread th1=new mythread(1);
mythread th2=new mythread(2);
mythread th3=new mythread(3);
th1.setDaemon(true);
th2.setDaemon(true);
th3.setDaemon(true);
th1.start();
th2.start();
th3.start();
System.out.println("Main thead finish");
}
}
Explanation….
In above program, the main thread is a user thread which creates three threads th1,th2,th3.So, all these will also be user threads.The statements......
Th1.setDaemon(true);
Th2.setDaemon(true);
Th3.setDaemon(true);
Change the user threads to daemon threads.So when the user thread ends,all the daemon threads also end with it.