Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create daemon threads?

Tags:

java

daemon

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

like image 205
Biju CD Avatar asked Aug 14 '09 09:08

Biju CD


2 Answers

java.lang.Thread.setDaemon(boolean)

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

like image 175
Michael Borgwardt Avatar answered Sep 22 '22 01:09

Michael Borgwardt


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();
like image 30
amoran Avatar answered Sep 23 '22 01:09

amoran