Java中isDaemon()方法的重要性?
守护程序线程是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");
}
}
//主类
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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语