What is a daemon thread in Java?
In Java, a daemon thread is a thread that runs in the background and does not prevent the program from exiting.
A daemon thread is typically used to perform tasks that are not critical to the program's main functionality, such as garbage collection or periodic cleanups.
To create a daemon thread in Java, you can use the setDaemon
method of the Thread
class. Here's an example of how you can create a daemon thread:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
// perform background tasks
}
}
});
thread.setDaemon(true);
thread.start();
}
}
This code defines a Thread
object and sets it to be a daemon thread using the setDaemon
method. The thread will then run in the background until the program exits.
It's important to note that daemon threads can be stopped at any time, as they are intended to be used for tasks that are not critical to the program's main functionality.
I hope this helps! Let me know if you have any questions.