Tuesday, May 24, 2016

Daemon thread

By default, any thread we create ourselves is User thread. JVM shutdown as soon as it sees that all users thread are finished. It automatically shuts down the daemon thread too.
To create Daemon thread, we use Thread.setDaemon(true)

class JavaDaemonThread {
      
    public static void main(String[] args) throws InterruptedException {
        Thread dt = new Thread(new DaemonThread(), "dt");
        dt.setDaemon(true);
        dt.start();
        //continue program
        Thread.sleep(30000);
        System.out.println("Finishing program");
    }

}

class DaemonThread implements Runnable{

    @Override
    public void run() {
        while(true){
            processSomething();
        }
    }

    private void processSomething() {
        try {
            System.out.println("Processing daemon thread");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}

When we execute this program, JVM creates first user thread with main() function and then a daemon thread. When main function is finished, the program terminates and daemon thread is also shut down by JVM.

Output:
1
2
3
4
5
6
7
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Finishing program


No comments:

Post a Comment