Daemon thread là luồng ưu tiên thấp chạy nền, chủ yếu do JVM tạo cho tác vụ nền như Garbage Collection (GC). Nếu không có user thread chạy, JVM thoát dù daemon thread còn chạy. Mục đích daemon thread là phục vụ user thread. isDaemon() xác định thread có phải daemon hay không.
Cú pháp
Public boolean isDaemon()
Ví dụ
class SampleThread implements Runnable {
public void run() {
if(Thread.currentThread().isDaemon())
System.out.println(Thread.currentThread().getName() + " is daemon thread");
else
System.out.println(Thread.currentThread().getName() + " is user thread");
}
}
// Main class
public class DaemonThreadTest {
public static void main(String[] args){
SampleThread st = new SampleThread();
Thread th1 = new Thread(st, "Thread 1");
Thread th2 = new Thread(st, "Thread 2");
th2.setDaemon(true); // đặt th2 thành daemon
th1.start();
th2.start();
}
}
Kết quả
Thread 1 is user thread Thread 2 is daemon thread