Java Thread setDaemon()方法

Thread类的setDaemon()方法用于将线程标记为守护程序线程或用户线程。 它的生命依赖于用户线程,即当所有用户线程都消亡时,JVM会自动终止该线程。必须在线程启动之前调用它。

如果在声明线程后调用setDaemon()方法,则此方法将抛出IllegalThreadStateException

语法

public final void setDaemon(boolean on)

参数

  • on - 如果为true,则将该线程标记为守护程序线程。

返回值

如果线程是守护进程线程,则此方法将返回true,否则返回false

异常

  • IllegalThreadStateException:如果线程处于活动状态。
  • SecurityException:如果当前线程无法修改线程。

示例

public class JavaSetDaemonExp1 extends Thread  
{    
    public void run()  
    {    
        //checking for daemon thread    
        if(Thread.currentThread().isDaemon())  
        {  
            System.out.println("daemon thread work");    
        }    
        else  
        {    
            System.out.println("user thread work");    
        }    
    }    
    public static void main(String[] args)  
    {    
        // creating three threads  
        JavaSetDaemonExp1 t1=new JavaSetDaemonExp1();   
        JavaSetDaemonExp1 t2=new JavaSetDaemonExp1();    
        JavaSetDaemonExp1 t3=new JavaSetDaemonExp1();    
        // set user thread t1 to daemon thread    
        t1.setDaemon(true);  
        //call run() method  
        t1.start();   
        // set user thread t2 to daemon thread    
        t2.setDaemon(true);  
        // start of threads   
        t2.start();    
        t3.start();    
    }    
}

执行上面示例代码,得到以下结果:

daemon thread work
daemon thread work
user thread work

示例二

在线程启动后调用setDaemon()方法时。

public class JavaSetDaemonExp2 extends Thread  
{    
    public void run()  
    {    
        System.out.println("Name of thread: "+Thread.currentThread().getName());    
        // //checking for daemon thread    
        System.out.println("Daemon: "+Thread.currentThread().isDaemon());  
    }    
    public static void main(String[] args)  
    {    
        // creating two threads   
        JavaSetDaemonExp2 t1=new JavaSetDaemonExp2();    
        JavaSetDaemonExp2 t2=new JavaSetDaemonExp2();    
        // call run() method   
        t1.start();   
        // this will throw exception here   
        t1.setDaemon(true);   
        // call run() method    
        t2.start();    
    }    
}

执行上面示例代码,得到以下结果:

Name of thread: Thread-0
Daemon: false
Exception in thread "main" java.lang.IllegalThreadStateException
    at java.lang.Thread.setDaemon(Thread.java:1359)
    at JavaSetDaemonExp2.main(JavaSetDaemonExp2.java:17)

上一篇: Java Runtime类 下一篇:无