Java 中 isDaemon() 方法的重要性?


守护线程是 java 中的低优先级线程,它在后台运行,主要由 JVM 创建,用于执行后台任务,例如垃圾回收 (GC)。

如果没有用户线程处于运行状态,那么即使守护线程正在运行,JVM 也会退出。守护线程的唯一目的是为用户线程服务。isDaemon() 方法可用于确定该线程是不是守护线程。

语法

Public boolean isDaemon()

示例

Open Compiler
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(); } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

Thread 1 is user thread
Thread 2 is daemon thread

更新于: 2023 年 11 月 23 日

463 次观看

开启你的 职业生涯

通过完成课程获得认证

开始
广告