Quantcast
Channel: What is a daemon thread in Java? - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by Tony for What is a daemon thread in Java?

$
0
0

Let's talk only in code with working examples. I like russ's answer above but to remove any doubt I had, I enhanced it a little bit. I ran it twice, once with the worker thread set to deamon true (deamon thread) and another time set it to false (user thread). It confirms that the deamon thread ends when the main thread terminates.

public class DeamonThreadTest {public static void main(String[] args) {    new WorkerThread(false).start();    //set it to true and false and run twice.    try {        Thread.sleep(7500);    } catch (InterruptedException e) {        // handle here exception    }    System.out.println("Main Thread ending");    }   }   class WorkerThread extends Thread {    boolean isDeamon;    public WorkerThread(boolean isDeamon) {        // When false, (i.e. when it's a user thread),        // the Worker thread continues to run.        // When true, (i.e. when it's a daemon thread),        // the Worker thread terminates when the main        // thread terminates.        this.isDeamon = isDeamon;        setDaemon(isDeamon);    }    public void run() {        System.out.println("I am a "+ (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));        int counter = 0;        while (counter < 10) {            counter++;            System.out.println("\tworking from Worker thread "+ counter++);            try {                sleep(5000);            } catch (InterruptedException e) {                // handle exception here            }        }        System.out.println("\tWorker thread ends. ");    }}result when setDeamon(true)=====================================I am a Deamon Thread    working from Worker thread 0    working from Worker thread 1Main Thread endingProcess finished with exit code 0result when setDeamon(false)=====================================I am a User Thread (none-deamon)    working from Worker thread 0    working from Worker thread 1Main Thread ending    working from Worker thread 2    working from Worker thread 3    working from Worker thread 4    working from Worker thread 5    working from Worker thread 6    working from Worker thread 7    working from Worker thread 8    working from Worker thread 9    Worker thread ends. Process finished with exit code 0

Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>