Daemon vs non-daemon threads

  1. Daemon Threads: You can think of them as the threads that maintains the environment and program, threads that are used by JVM for itself. Like the thread that does garbage collection for example. But these kinds of threads can also be created in the application by the programmer.
  2. Non-daemon Threads: These are user threads. For example, initial thread that starts running at the execution of main() function is a non-daemon thread.
public class SoYouThinkYouCanThread extends Thread {
public static void main(String[] args) {
System.out.println("Hello!");
SoYouThinkYouCanThread sytyct = new SoYouThinkYouCanThread();

// This is by default is set to false. It inherits this from the running
// parent thread.
sytyct.setDaemon(false);

sytyct.start();
System.out.println("Good bye!");
}
public void run() {
System.out.println("Warming up!");
boolean shouldIKeepRunning = true; while (shouldIKeepRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
System.out.println("Oops!");
}
System.out.println("Running!");
}
}
}
Hello!
Good bye!
Warming up!
Hello!
Good bye!
Warming up!
Running!
Running!
Running!
Running!
...

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mehmet Akcay

Mehmet Akcay

a geek who loves to understand the reasons behind things... and colors... Colors are cool.