Java Thread isDaemon()方法

2019-10-16 22:24:34

Thread類的isDaemon()方法檢查執行緒是否是守護程式執行緒。 如果執行緒是守護行程執行緒,則此方法將返回true,否則返回false

語法

public final boolean isDaemon()

返回值

如果執行緒是守護行程執行緒,則此方法將返回true,否則返回false

public class JavaIsDaemonExp 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  
        JavaIsDaemonExp t1=new JavaIsDaemonExp();   
        JavaIsDaemonExp t2=new JavaIsDaemonExp();    
        JavaIsDaemonExp t3=new JavaIsDaemonExp();    
        // set user thread t1 to daemon thread    
        t1.setDaemon(true);  
        //starting all the threads   
        t1.start();   
        t2.start();    
        t3.start();    
    }    
}

執行上面範例程式碼,得到以下結果:

daemon thread work
user thread work
user thread work