Home » Java programming language

Java Thread Class final void setDaemon(boolean thread_status) method with Example

Java Thread Class final void setDaemon(boolean thread_status) method: Here, we are going to learn about the final void setDaemon(boolean thread_status) method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 25, 2019

Thread Class final void setDaemon(boolean thread_status)

  • This method is available in package java.lang.Thread.setDaemon(Boolean thread_status).
  • This method is used to set the current thread as a Daemon thread.
  • Daemon thread is the thread which runs in the background.
  • This method is not static so we cannot access this method with the class name too.
  • This method is final we can't override this method in child class.
  • The return type of this method is void so it does not return anything.
  • This method does not raise an exception if the current thread can't modify this thread.

Syntax:

    final void setDaemon(boolean thread_status){
    }

Parameter(s):

We pass only one object (thread_status) as a parameter in the method of the Thread. Here thread_status is of the boolean type so the value will be true or false if set true in setDaemon(true) method so it means this thread is a daemon thread and else set false in setDaemon(false) method so it means this thread is not a daemon thread.

Return value:

The return type of this method is void, it does not return anything.

Java program to demonstrate example of setDaemon() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/

import java.lang.Thread;

class SetDaemonThread extends Thread {
    //Override run() method of Thread class 
    public void run() {

        // To check the thread is daemon
        if (Thread.currentThread().isDaemon()) {

            //Code for Daemon thread 
            System.out.println(Thread.currentThread().getName() + " is a daemon thread");
        } else {
            System.out.println(Thread.currentThread().getName() + " is not a daemon thread");
        }
    }

    public static void main(String[] args) {
        // creating three object of the class SetThreadDaemon
        SetDaemonThread d1 = new SetDaemonThread();
        SetDaemonThread d2 = new SetDaemonThread();
        SetDaemonThread d3 = new SetDaemonThread();

        // d2 is a daemon thread which is set by setDaemon(true) method
        d2.setDaemon(true);

        // By using start() method we will start execution of the thread
        d1.start();
        d2.start();
        d3.start();
    }
}

Output

E:\Programs>javac SetDaemonThread.java

E:\Programs>java SetDaemonThread
Thread-0 is not a daemon thread
Thread-1 is a daemon thread
Thread-2 is not a daemon thread



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.