Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของเมธอด isDaemon() ใน Java


Daemon thread เป็น low-priority thread ใน Java ทำงานเบื้องหลัง สร้างโดย JVM ส่วนใหญ่สำหรับงาน background เช่น Garbage Collection (GC) หากไม่มี user thread รัน JVM จะจบได้แม้ daemon threads จะยังทำงานอยู่ วัตถุประสงค์เดียวของ daemon thread คือ service ให้ user threads เมธอด isDaemon() ใช้ตรวจสอบว่าเธรดนั้นเป็น daemon thread หรือไม่

ไวยากรณ์

public boolean isDaemon()

ตัวอย่าง

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); // set the thread th2 to daemon.
        th1.start();
        th2.start();
    }
}

ผลลัพธ์

Thread 1 is user thread Thread 2 is daemon thread