Java中的守护程序线程示例
时间:2020-02-23 14:36:12 来源:igfitidea点击:
守护程序线程是低优先级背景线程,它为用户线程提供服务。
它的生命取决于用户线程。
如果没有用户线程正在运行,则即使守护程序线程正在运行,JVM也可以退出。
JVM不要等待守护程序线程完成。
守护程序线程执行后台任务,如垃圾收集,终结器等。
守护程序线程的唯一目的是为用户线程服务,因此如果没有用户线程,则没有JVM运行这些线程,这就是为什么JVM退出后没有用户线程。
两个与守护程序线程相关的方法
public void setdaemon(布尔状态):此方法可用于将线程标记为用户或者守护程序线程。
如果我们将SetDaemon(true)放置,则将线程作为守护程序。
Public boolean isDaemon()
此方法可用于检查线程是否是守护程序。
守护程序线程示例:
package org.arpit.theitroad; class SimpleThread 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 DaemonThreadMain { public static void main(String[] args){ SimpleThread st=new SimpleThread(); Thread th1=new Thread(st,"Thread 1");//creating threads Thread th2=new Thread(st,"Thread 2"); Thread th3=new Thread(st,"Thread 3"); th2.setDaemon(true);//now th2 is daemon thread th1.start();//starting all threads th2.start(); th3.start(); } }
运行上面的程序时,我们将得到以下输出:
Thread 1 is user thread Thread 3 is user thread Thread 2 is daemon thread
Please note that you can not convert user thread to daemon thread once it is started otherwise it will throw IllegalThreadStateException.
package org.arpit.theitroad; class SimpleThread 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 DaemonThreadMain { public static void main(String[] args){ SimpleThread st=new SimpleThread(); Thread th1=new Thread(st,"Thread 1");//creating threads Thread th2=new Thread(st,"Thread 2"); Thread th3=new Thread(st,"Thread 3"); th1.start();//starting all threads th2.start(); th3.start(); th2.setDaemon(true);//now converting user thread to daemon thread after starting the thread. } }
运行上面的程序时,我们将得到以下输出:
Thread 1 is user threadException in thread “main" Thread 2 is user thread Thread 3 is user thread java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Thread.java:1388) at org.arpit.theitroad.DaemonThreadMain.main(DaemonThreadMain.java:28)