-1

Can anyone tell me how we can create Daemon thread in Java?

I mean the syntax and how it can be used and modified.

Saurabh Shubham
  • 43
  • 2
  • 14

1 Answers1

1

JVM garbage collection thread is a typical Daemon Thread, and you can create daemon thread just like the normal thread and call such thread setDaemon(true) and here i make a simple demo:

/**
 * Created by crabime on 11/10/16.
 */
public class DaemonTest extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++){
            System.out.println(getName() + "  " + i);
        }
    }

    public static void main(String[] args) {
        DaemonTest d = new DaemonTest();
        d.setDaemon(true);
        d.start();
        try {
            Thread.sleep(200);//after 200 million seconds, main thread ends and no matter DaemonTest thread run to the end or not, it will stop 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
Crabime
  • 644
  • 11
  • 27