Types of Threads in Java: User and Daemon Threads

threads in java

Java is not like any other language. Java is an object-oriented programming language, and it is class-based. Designer James Gosling threads in java and Developer Sun Microsystems released it 24 years ago in 1995.  Java provides built-in support for multithreading.

Here we will talk about types of threads in Java and details about them. They are a lightweight process. There are two kinds of threads in Java we find. The first one is User Thread, and the other one is the Daemon Thread. We know that a user thread runs in the foreground, and it always has a high priority. On the other hand, the Daemon threads in Java are low priority threads and ever run in the background.

User threads do some specific tasks, and Daemon threads do supporting jobs.

So in this blog, we are going to explain some of the crucial differences between User Threads and Daemon Threads and other related things of java threads.

What Are Threads in Java

A thread usually is a program in execution that is performing some fixed task. You can create a thread automatically and in Java. A thread started when Java Virtual Machine called JVM loads, and this Thread is defined as the main Thread. We know that Threads are an independent path of execution within the program. There are a lot of threads that may run concurrently within a program, but threads in Java are built and controlled via java thread class.

Creating a thread is accomplished by executing an interface and extending a class in Java. You already know that the Thread is a lightweight process that helps us in running a task in parallel. It provides the maximum utilization of the CPU and increases the CPU performance. Threads enable Java application faster by doing a lot of things at the same time.

Why We Use Threads in Java

If I say in a word, we use Threads to enable Java faster to do multiple things at a time. Threads help you to achieve parallelism in Java programs. You know CPU is speedy, and today it even contains numerous cores, that means your pricy hardware will keep idle for most the time. You can take full advantage of multiple cores by serving more clients faster. Because nowadays, response time matters a lot, and that is the reason you have multiple cores. By the way, if your application does not make full use of all the resources, then there is no meaning for adding them.

However, there is one more purpose of enabling Threads in Java is to do multiple tasks simultaneously. Such as in the GUI application, you want to draw screens at the same time you want to capture user action too. Java alone can stitch and catch things together. You can hold more than one thread together and make something practical. If I say in the simplest terms, Threads in Java is a process of an executing program.

The Java Thread Model

Here we will talk about the Java thread model. The Java run-time system depends on many factors. Threads decrease inefficiency by preventing the waste of CPU cycles.

Threads model exists in several states. Such as:

  • New: A thread will be in a new state when you create an instance of Thread class.
  • Runnable: The Java thread always in running state.
  • Suspended: A running thread temporarily suspends its activity. And then, you can resume a suspend thread by allowing it to start up where it left off.
  • Blocked: When a Java thread waits for a resource, it can be prevented.
  • Terminated: A thread halts its execution immediately at any given time when a thread is terminated. By the way, you cannot resume once a thread is terminated.
READ  What is Black Box Testing

So, that’s all about the Java thread model and its state.

 

What Happens When Threads In Java Are Invoked?

You will get two types of paths of execution whenever you invoked a thread. The first path will execute the Thread, and the other one will follow the statement after the spread invocation. There are a separate stack and memory space for each Thread.

Risk Factor:

If you want a consistent view of data accessing common variables, proper coordination is required. And try to use fewer threads in Java as overuse of java thread can be hazardous for programs’ task and its maintainability.

How To Create Threads In Java

There are two ways available for creating java thread.

  1. Extending the Java thread class.
  2. Implementing the Java runnable interface.

 

  1. Extending The Java Thread Class.

Thread class supplies constructors and methods to create and perform an operation in a thread. Thread class always extends object class and implements the runnable interface.

  • The class should extend the java thread class.
  • The class should override the run() method.
  • The expected functionality by the Thread is written in the run() method.

Some Commonly Used Constructors Of The Thread Class In Java:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r, String name)

Some Commonly Used Methods Of Thread Class In Java:

  • public void join(): it waits for a thread to die.
  • public void join(long milliseconds): it waits for a thread to die for the specified milliseconds.
  • public void run(): it is used to do an action for a thread.
  • public void start(): it begins the execution of the Thread. JVM usually calls the run() method on the Thread.
  • public void sleep(long milliseconds): it causes the executing Thread to sleep for a specific number of milliseconds.
  • public int get priority(): it returns the priority of the Thread.
  • public int setPriority(int priority): It changes the priority of a thread.
  • public String getName(): it will return the name of the Thread.
  • public void setName(String name): it changes the name of the Thread.
  • public Thread currentThread(): it returns the reference of executing Thread.
  • public int getId(): it returns the id of a thread.
  • public Thread.State getState(): it returns the state of a thread.
  • public boolean isAlive(): it tests if the Thread is alive.
  • public void yield(): it causes the executing thread object to pause and allow other threads to do.
  • public void suspends (): it suspends the suspended Thread.
  • public void resumes(): it resumes the suspended Thread.
  • public void stop(): it stops the Thread.
  • public boolean daemon(): it tests if the Thread is a daemon thread.
  • public void setDaemon(boolean b): it marks the Thread as daemon or user thread.
  • public boolean isInterrupted(): it tests if a thread has been interrupted.
  • public static boolean interrupted(): it tests if the current Thread has been interrupted.
  • public void interrupt(): it interrupts the Thread.

 

  1. Implementing The Java Runnable Interface.

Classes should implement the Runnable interface, whose examples are intended to be executed by a thread. The Runnable interface has only a method called run().

  • public void run(): it is used to act as the Thread.

Starting Thread

start() method is a thread class, and it is used to start for a newly built thread. It performs the following tasks:

  • It starts a new thread with a new call stack.
  • This Thread moves from the initial state to the runnable state.
  • The thread target run() method will run when your Thread gets a chance to execute.

Extending The Java Thread Class Example.

class Multi extends Thread{

public void run(){

System.out.println(“thread is running…”);

}

public static void main(String args[]){

Multi t1 = new Multi();

t1.start();

}

}

 

Implementing The Java Runnable Interface Example.

class Multi3 implements Runnable {

public void run(){

System.out.println(“thread is running…”);

}

 

public static void main(String args[]){

Multi3 m1 = new Multi3();

Thread t1 = new Thread(m1);

t1.start();

}

}

 

Your class object will not be treated as a thread object if you are not extending the Thread class. So, you will be required to explicitly create a Thread class object as we will also pass the object of your class that implements Runnable so that your class run() method can execute.

 

Extends Thread Class Vs. Implements Runnable Interface

Extending the Thread class will not let you continue other classes. The reason is the single inheritance feature in Java. By the way, this Thread will give you a similar code structure. After implementing Runnable, you will gain better object-oriented design and consistency and avoid the single inheritance problems too.

READ  System IDLE Processes and PC Performance

You may want to achieve the basic functionality of a thread. You will simply implement the Runnable interface and override run() method. By the way, if you want to do something serious with a thread object as it has other methods like suspend(), resume(). These are not available in the Runnable interface then you can prefer to extend the Thread class.

Details Difference Between User Threads And Daemon Threads In Java

  1. Creation: Any kind of Thread you create from the primary method is a user thread. On the other hand, when you will create a daemon thread, you need to call the setDaemon method.
  2. JVM exit: JVM usually does not exist until all user threads complete their execution while JVM will without waiting for daemon thread to finish their work. In short, JVM will not allow for daemon thread to finish, but it remains for User Thread.
  3. Thread Priority: Here, user thread gets high priority compared to daemon thread. That means they will not get CPU as quickly as a user thread may get.
  4. Termination of Thread: JVM forces daemon thread to terminate if the user threads have ended their execution, but the user threads are closed by application. User thread may keep running by JVM running, but a daemon thread will not stay running by the JVM. And this one is the most critical diversity between a user thread and daemon thread.
  5. Usage: You cannot use daemon threads for any critical task. Only a user can do an emergency task. Daemon usually works for background tasks, which are not important enough.
  6. JVM does not force the user threads to terminate. This will wait for the user thread to terminate. By the way, JVM will force the daemon to terminate if all the user threads can finish their task.

 

In Short: The Main Difference Between User Threads (Non-Daemon) And Daemon Threads In Java

 

User Threads Daemon Threads
JVM usually waits for user threads to complete their task. And it will not exit until all user threads achieve their mission. On the other hand, JVM will not wait for the daemon threads to complete their work. And it will exit as soon as all user threads finish their task.
The user threads are foreground threads. But daemon threads are background threads.
It is created from the Main() method. Daemon threads created from the setDaemon(true) method.
The User thread has priority as compared to Daemon threads. It is a low priority thread.
You can use user threads in Java for critical tasks. Daemon threads are unable to perform any kinds of critical tasks.
The user threads are created from the application. Mostly it is created by the JVM.

 

The life of the user thread is independent. The life of daemon threads depends on the user threads.
The user threads are mostly designed for specific tasks. On the other hand, the daemon threads are created to support the user threads.

 

Some Instances Of User Thread And Daemon Thread In Java

Below we will show isDaemon() and setDaemon() methods usage.

public class DaemonThreadExample extends Thread {

 

    public static void main(String args[]) {

        System.out.println(“Thread name is : “+ Thread.currentThread().getName());

        //Checking main thread is daemon or non-daemon thread(user thread)

        System.out.println(“Is main thread daemon ? : “+ Thread.currentThread().isDaemon());

        

        // Creating two threads (they are user(non-daemon) threads)

        DaemonThreadExample t1 = new DaemonThreadExample();

        DaemonThreadExample t2 = new DaemonThreadExample();

       

        // Converting t1(user)thread to daemon thread

        t1.setDaemon(true);

       

        // Starting t1 and t2 threads

        // Executing run method

        t1.start();

        t2.start();

    }

   

    public void run() {

        // Checking threads are daemon or not

        if (Thread.currentThread().isDaemon()) {

            System.out.println(Thread.currentThread().getName()+” is Daemon Thread”);

        }

        else {

            System.out.println(Thread.currentThread().getName()+” is Non Daemon Thread”);           

        }

       

    }

}

 

Leave a Reply

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

Read previous post:
technical feasibility
7 Assessing the Technical Feasibility

Technical feasibility generally relates to your indentation to deliver service or a product to your customers or buyers. Technical feasibility...

Close