Java 中 isDaemon() 方法的重要性?
javaobject oriented programmingprogramming更新于 2024/7/26 12:47:00
守护线程是 Java 中的低优先级线程,它在后台运行,主要由 JVM 创建,用于执行垃圾收集 (GC) 等后台任务。如果没有用户线程正在运行,那么即使守护线程正在运行,JVM 也会退出。守护线程的唯一目的是为用户线程提供服务。isDaemon() 方法可用于确定线程是否为守护线程。
语法
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