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 出阁宴祝福语姐姐简短