6

Can a java programmer can create daemon threads manually? How is it?

Gray
  • 115,027
  • 24
  • 293
  • 354
Biju CD
  • 4,999
  • 11
  • 34
  • 55

4 Answers4

12

java.lang.Thread.setDaemon(boolean)

Note that if not set explicitly, this property is "inherited" from the Thread that creates a new Thread.

Gray
  • 115,027
  • 24
  • 293
  • 354
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
6

You can mark a thread as a daemon using the setDaemon method provided. According to the java doc:

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.

This method first calls the checkAccess method of this thread with no arguments. This may result in throwing a SecurityException (in the current thread).

Here an example:

Thread someThread = new Thread(new Runnable() {
    @Override
    public void run() {
        runSomething();
    }
});
someThread.setDaemon(true);
someThread.start();
Community
  • 1
  • 1
amoran
  • 1,079
  • 1
  • 10
  • 6
0
class mythread1 implements Runnable {
  public void run() {
    System.out.println("hii i have set thread as daemon");
  }


  public static void main(String []arg) {
    mythread1 th=new mythread1();
    Thread t1 = new Thread(th);
    t1.setDaemon(true);
    t1.start();
    System.out.println(t1.isDaemon());
  }
}
Manuel
  • 3,828
  • 6
  • 33
  • 48
Rohit
  • 37
  • 1
  • 1
  • 6
-4

Yes you can

Thread thread = new Thread(  
  new Runnable(){  
    public void run(){  
      while (true)
        wait_for_action();
    }  
  }  
);  
thread.start(); 
Lliane
  • 831
  • 2
  • 7
  • 15
  • 1
    class Devil extends Thread { Devil() { setDaemon( true ); start(); } public void run() { // Perform evil tasks ... } } I got this one... Have u heard about this.. – Biju CD Aug 14 '09 at 09:26