What is a daemon thread in Java?

Asked 1 years ago, Updated 1 years ago, 101 views

Someone please explain the daemon thread.

multithreading java

2022-09-22 22:33

1 Answers

Boolean isDaemon() // Check if the thread is a daemon thread.
void setDaemon(boolean on) // thread to daemon thread or user thread
                            // Change it.
import java.util.*;

class example implements Runnable{
    static boolean autoSave = false;

    public static void main(String[] args) {
        Thread t = new Thread(new example());
        t.setDaemon(true);
        t.start();

        for(int i=1; i<=20; i++)
        {
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){}
            System.out.println(i);

            if(i==5)
                autoSave = true;
        }
        System.out.println ("Exit the program")
    }

    @Override
    public void run() {
        while(true)
        {
            try{
                Thread.sleep(3 * 1000);
            }catch(InterruptedException e){}

            if(autoSave)
                autoSave();
        }
    }

    private void autoSave() {
        System.out.println ("The job file has been automatically saved."");
    }
}

If it hadn't been t.setDaemon(true); here, we would have kept going in an infinite loop.


2022-09-22 22:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.