How to Create a Daemon Thread in Java


In this example we will show how to make a thread as a daemon thread in Java.

Source Code

package com.beginner.examples;

public class DaemonThreadExample extends Thread{
	Thread thread1;
    public DaemonThreadExample(Thread thread1){
    	this.thread1 = thread1;
    	// make the thread as a daemon thread
    	setDaemon(true);
    }
    @Override
    public void run(){
    	System.out.println(Thread.currentThread().getName());
        System.out.println("Is it a daemon thread? " + isDaemon());
    }
    public static void main(String[] args){
    	Thread thread1 = Thread.currentThread();
        DaemonThreadExample d = new DaemonThreadExample(thread1);
        d.start();
    }
}

Output:

Thread-0
Is it a daemon thread? true
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments