Daemon Thread in Java

Daemon Thread in Java with Examples

In this article, I am going to discuss Daemon Thread in Java with examples. Please read our previous article where we discussed Thread Priority in Java. At the end of this article, you will understand what exactly are Daemon Threads in Java and when and how to create and use Daemon Threads with examples.

Daemon Thread in Java:

Daemon Threads are called background Threads which work in the background and provide the service for other threads. Daemon Threads will run only when other threads are available otherwise JVM will shut down all the daemon threads.

By default main thread and all its child threads are non-daemon threads. But if we want to make the user-defined thread as a daemon thread, we have to use the setDaemon() method. For example Garbage Collector

Sample Program to Understand Daemon Thread in Java:
class MyThreadDaemon implements Runnable
{
    double num;
    public void run ()
    {
        for (int i = 1; i <= 10000; i++)
        {
         num = Math.random ();
         //System.out.println("User Thread value:" + num);
         try
         {
             Thread.sleep (1000);
         } catch (InterruptedException ie)
         {
         }
        }
    }
}

public class DaemonThread
{
    public static void main (String[]args)
    {
        MyThreadDaemon mt = new MyThreadDaemon ();
        Thread t = new Thread (mt);
        t.setDaemon (true);
        t.start ();
        for (int i = 1; i <= 5; i++)
        {
         System.out.println ("Main Thread value:" + mt.num);
         try
         {
             Thread.sleep (1000);
         } catch (InterruptedException ie)
         {
         }
        }
    }
}

Output:

Program to Understand Daemon Thread in Java

Note: We must call the t.setDaemon(true) method before starting the thread otherwise it will throw a run time exception called IllegalThreadStateException and user thread won’t become as Daemon Thread. We cannot change our main Thread as Daemon Thread.

Types of Threads in Java:

Orphan Thread: If any thread is running without any help of its parent thread then it is called Orphan Thread. To create this kind of thread we can use join() method.

Helper Thread: If any thread is waiting and giving a chance to other threads to execute, then these threads are called Helper Threads. When we call sleep() or join() or wait() method, then that waiting thread is called Helper Thread.

Selfish Thread: If any thread is running until the completion of its job or executing completely then it is called Selfish Thread.

Starving Thread: If any thread is waiting for a long time then it is called Starving Threads. Generally, we can observe this kind of selfish threads or starving threads in synchronization or when we use wait() and notify() method.

Green Threads: Green Threads are called JVM level Threads which are used to allocate the resources to other threads.

Native Threads: Native Threads are called at OS-level Threads which are also responsible for allocating the resources to other threads. Here allocation of resources is efficient than Green Threads.

Daemon Threads: Daemon Threads are the background threads which work in the background and provide service for other threads.

Write a Program to create multiple threads that are acting on different objects and having the same job.
class MyThread01 implements Runnable{
 public void run() {
  Thread t = Thread.currentThread();
  for(int i=1; i<=10; i++) {
   System.out.println(t.getName()+"Thread value:"+1);
  }
 }
}
public class MultiThreading1 {

 public static void main(String[] args) {
  MyThread01 mt1 = new MyThread01();
  MyThread01 mt2 = new MyThread01();
  MyThread01 mt3 = new MyThread01();
  Thread t1 = new Thread(mt1);
  Thread t2 = new Thread(mt2);
  Thread t3 = new Thread(mt3);
  t1.start();
  t2.start();
  t3.start();
 }
}
Write a Program to create multiple threads which are acting on different objects and having a different job.
class EvenThread implements Runnable{
 public void run() {
  for(int i=0; i<=20; i=i+2) {
   System.out.println("Even Thread Value:"+i);
   try {
    Thread.sleep(1000);
   }
   catch(InterruptedException ie) {}
  }
 }
}
class OddThread implements Runnable{
 public void run() {
  for(int i=1; i<=20; i=i+2) {
   System.out.println("Odd Thread Value:"+i);
   try {
    Thread.sleep(1000);
   }
   catch(InterruptedException ie) {}

 }
 }
}
public class MultiThreading2 {
 public static void main(String[] args) {
  EvenThread et = new EvenThread();
  OddThread ot = new OddThread();
  Thread t1 = new Thread(et);
  Thread t2 = new Thread(ot);
  t1.start();
  t2.start();
  for(int i=1; i<=10; i++) {
   System.out.println("Main Thread Value:"+i);
   try{Thread.sleep(1000);}
   catch(InterruptedException ie) {}
  }
 }
}

Note: When we execute multiple threads at the same time simultaneously then we will never get the same output for every execution because ThreadScheduler will decide which thread should execute in the next step.

Write a Program to create multiple threads that are acting on the same objects.
class CollegeThread implements Runnable{
 int seats;
 CollegeThread(int seats){
  this.seats=seats;
 }
 public void run() {
  Thread ct = Thread.currentThread();
  String tname = ct.getName();
  System.out.println(tname+" No. of seats available before allotment:"+seats);
  if(seats>0) {
      try {
    Thread.sleep(1000);
   }
   catch(InterruptedException ie) {}
  System.out.println("Seat is alloted to:"+tname);
  seats = seats-1;
  }
  else {
   System.out.println("Seat is not alloted to:"+tname);
  }
  System.out.println(tname+" No. of seats available after allotment:"+seats);
 }
}
//Allotment Class
public class Main {
 public static void main(String[] args) {
  CollegeThread ct = new CollegeThread(1);
  Thread t1 = new Thread(ct);
  Thread t2 = new Thread(ct);
  Thread t3 = new Thread(ct);
  t1.setName("Sachin");
  t2.setName("Sehwag");
  t3.setName("Dhoni");
  t1.start();
  t2.start();
  t3.start();
 }
}

Output:

Write a Program to create multiple threads which are acting on same objects.

Note: In the above program when we have 50 seats then the seat is allotted for all the 3 people. But when we have only 1 seat then only one person has to get the seat, but the seat is again allotted for all the 3 people, which is nothing but “Data Inconsistency Problem”.

What is Data Inconsistency Problem?

When we execute multiple Threads that are acting on the same object at the same time simultaneously then there is a chance of occurring data inconsistency problem in the application.

Data inconsistency problem will occur because one thread is updating the value at the same time and another thread is using old value. To resolve this data inconsistency problem we have to synchronize the object on which multiple Threads are acting.

In the next article, I am going to discuss Thread Synchronization in Java with Examples. Here, in this article, I try to explain Daemon Thread in Java with Examples. I hope you enjoy this Daemon Thread in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *