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 官宣新年祝福语简短