Java.lang.Thread.setDaemon() Method

Advertisements


Description

The java.lang.Thread.setDaemon() method marks this thread as either a daemon thread or a user thread.The Java Virtual Machine exits when the only threads running are all daemon threads.This method must be called before the thread is started.

Declaration

Following is the declaration for java.lang.Thread.setDaemon() method

public final void setDaemon(boolean on)

Parameters

  • on -- if true, marks this thread as a daemon thread.

Return Value

This method does not return any value.

Exception

  • IllegalThreadStateException -- if this thread is active.

  • SecurityException -- if the current thread cannot modify this thread.

Example

The following example shows the usage of java.lang.Thread.setDaemon() method.

package com.tutorialspoint;

import java.lang.*;

class adminThread extends Thread {

   adminThread() {
      setDaemon(false);
   }

   public void run() {
      boolean d = isDaemon();
      System.out.println("daemon = " + d);
   }
}

public class ThreadDemo {

  public static void main(String[] args) throws Exception {
    
    Thread thread = new adminThread();
    System.out.println("thread = " + thread.currentThread());
    thread.setDaemon(false);
   
    // this will call run() method
    thread.start();
  }
} 

Let us compile and run the above program, this will produce the following result:

thread = Thread[main,5,main]
daemon = false



Advertisements
Advertisements