Java - Set the thread as a non-daemon thread

Introduction

Since the program has a non-daemon thread, the JVM will keep running the application, even after the main() method finishes.

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::print);
    t.setDaemon(false);
    t.start();
    System.out.println("Exiting main method");
  }

  public static void print() {
    int counter = 1;
    while (true) {
      try {
        System.out.println("Counter:" + counter++);
        Thread.sleep(2000); // sleep for 2 seconds
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

Related Topic