Daemon thread in Java | Code Factory

public final void setDaemon(boolean on)Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.This method must be invoked before the thread is started.Parameters:
on - if true, marks this thread as a daemon thread
Throws:
IllegalThreadStateException - if this thread is alive
public final boolean isDaemon()Tests if this thread is a daemon thread.Returns:
true if this thread is a daemon thread; false otherwise.
package com.codeFactory;/**
* @author code.factory
*
*/
public class DaemonTest {
public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending") ;
}
}class WorkerThread extends Thread {public WorkerThread() {
// When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
setDaemon(true);
}
public void run() {
int count = 0;
while (true) {
System.out.println("Hello from Worker "+count++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
}
}
Hello from Worker 0
Hello from Worker 1
Main Thread ending
package com.codeFactory;/**
* @author code.factory
*
*/
public class DaemonTest extends Thread {
public DaemonTest(String name) {
super(name);
}

public void run() {
if(Thread.currentThread().isDaemon()) {
System.out.println(getName() + " is Daemon Thread");
} else {
System.out.println(getName() + " is User Thread");
}
}

public static void main(String[] args) {
DaemonTest d1 = new DaemonTest("d1");
DaemonTest d2 = new DaemonTest("d2");
d1.setDaemon(true);
d1.start();
d2.start();
}
}
d1 is Daemon Thread
d2 is User Thread

--

--

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