Search code examples
javamultithreadingdaemon

Daemon Thread more than one?


This is a very short and simple question, but couldn't get the answer from anywhere.

More than one daemon threads can be created?


Solution

  • Yes. You can simply test it with code like

    Thread t1 = new Thread(()->{
        while(true){
            System.out.println("daemon1");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {}
        }
    });
    t1.setDaemon(true);
    
    Thread t2 = new Thread(()->{
        while(true){
            System.out.println("daemon2");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {}
        }
    });
    t2.setDaemon(true);
    
    t1.start();
    t2.start();
    
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (Exception e) {}
    System.out.println("main thread stopped");
    

    Output:

    daemon1
    daemon2
    daemon1
    daemon2
    daemon1
    daemon1
    daemon1
    daemon2
    daemon1
    main thread stopped
    

    As you see two daemons ware running at the same time. Also since there ware no other non-daemon threads, application stopped.