Java Daemon Thread
Java Daemon Thread
WhiteboardWe tested
this page and blocked content comingJobs
from
Home AI Assistant Online Compilers Tools Art
potentially dangerous or risky sites. Allow this content View all block
only if you're sure it comes from safe sites.
A Daemon thread is a service provider thread and should not be used as user
thread.
JVM automatically closes the daemon thread(s) if no active thread is present and
revives it if user threads are active again.
A daemon thread cannot prevent JVM to exit if all user threads are done.
package com.tutorialspoint;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getName()
+ ", is Daemon: " + Thread.currentThread().isDaemon());
}
public void start () {
super.start();
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
ThreadDemo thread3 = new ThreadDemo();
thread1.start();
thread2.start();
thread3.start();
}
}
Output
Example 1
In this example, we've created a ThreadDemo class which extends Thread class. In main
method, we've created three threads. As we're setting one thread as daemon thread,
one thread will be printed as daemon thread.
Page 3 of 6
package com.tutorialspoint;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
Output
Example 2
In this example, we've created a ThreadDemo class which extends Thread class. In main
method, we've created three threads. Once a thread starts, it cannot be set as daemon
thread. As we're setting one thread as daemon thread after it started, a runtime
exception will be raised.
Page 4 of 6
We tested this page and blocked content coming from Open Compiler
potentially dangerous or risky sites. Allow this content
only if you're sure it comes from safe sites.
package com.tutorialspoint;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getName()
+ ", is Daemon: " + Thread.currentThread().isDaemon());
}
public void start () {
super.start();
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
ThreadDemo thread3 = new ThreadDemo();
thread1.start();
thread2.start();
thread3.start();
thread3.setDaemon(true);
}
}
Output
TOP TUTORIALS
Python Tutorial
Page 5 of 6
Java Tutorial We tested this page and blocked content coming from
C++ Tutorial potentially dangerous or risky sites. Allow this content
only if you're sure it comes from safe sites.
C Programming Tutorial
C# Tutorial
PHP Tutorial
R Tutorial
HTML Chapters
Tutorial Categories
CSS Tutorial
JavaScript Tutorial
SQL Tutorial
TRENDING TECHNOLOGIES
Docker Tutorial
Kubernetes Tutorial
DSA Tutorial
Unix Tutorial
CERTIFICATIONS
DevOps Certification