Java — Daemon Threads | Code Factory

/* Tests if this thread is a daemon thread. */
public final boolean isDaemon()
/* 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.
true - marks this thread as a daemon thread
false - marks this thread as a non-daemon/user thread*/
public final void setDaemon(boolean on)
package com.example.thread;/**
* @author code.factory
*
*/
public class DaemonTest extends Thread {
public static void main(String... args) {
System.out.println(Thread.currentThread().isDaemon());
//Thread.currentThread().setDaemon(true); // RE : IllegalThreadStateException
DaemonTest d = new DaemonTest();
System.out.println(d.isDaemon());
d.setDaemon(true);
System.out.println(d.isDaemon());
}
}
false
false
true
package com.example.thread;/**
* @author code.factory
*
*/
public class DaemonTest {
public static void main(String... args) {
MyThread t = new MyThread();
t.setDaemon(true); // #1
t.start();
System.out.println("Main End");
}
}
class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Main End
Child Thread
@Deprecated
public final void stop()
@Deprecated
public final void suspend()
@Deprecated
public final void resume()

--

--

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