728x90
Application 이 종료될 때 JVM에 의해서 종료되는 Thread를 말한다.
보통 사용용도는 resource manager 또는 service 를 수행하는 중요도가 낮은 역할의 실행을 무한으로 돌릴때 사용한다.
가장 대표적인 예가 garbage collector 이다.
Java has a special kind of thread called daemon thread.
- Only executes when no other thread of the same program is running.
- JVM ends the program finishing these threads, when daemon threads are the only threads running in a program.
- Daemon threads shut down any time in between their flow, Non-daemon i.e. user thread executes completely.
- Daemon threads executes on low priority.
- Daemon threads are threads that run intermittently in background as long as other non-daemon threads are running.
- When all of the non-daemon threads complete, daemon threads terminates automatically.
- Daemon threads are service providers for non-threads running in the same process.
- JVM do not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is crated by us.
- Daemon threads acts as services in Windows.
What are daemon threads used for?
Normally used as service providers for normal threads. Usually have an infinite loop that waits for the service request or performs the tasks of the thread. They can’t do important jobs. (Because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. )
public class DaemonThread extends Thread {
public void run() {
System.out.println("Entering run method");
try {
System.out.println("In run Method: currentThread() is" + Thread.currentThread());
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException x) {}
System.out.println("In run method: woke up again");
}
} finally {
System.out.println("Leaving run Method");
}
}
public static void main(String[] args) {
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) {}
System.out.println("Leaving main method");
}
}
OutPut:
C:\java\thread>javac DaemonThread.java
C:\java\thread>java DaemonThread
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method
C:\j2se6\thread>
728x90
728x90