简体   繁体   中英

How can i make the main Thread as Daemon Thread in java?

I want to make the main thread as daemon thread but it show me IllegalThreadStateException . Is there any way to do that?

public class DeamonThreads {

    public static void main(String[] args) {
        System.out.println("Main Started");
        System.out.println("Thread type deamon = " + Thread.currentThread().isDaemon());
        Thread.currentThread().setDaemon(true);
        System.out.println("Thread type deamon = " + Thread.currentThread().isDaemon());
        System.out.println("Main End");
    
    }
}

Output

Main Started
Thread type deamon = false
Exception in thread "main" java.lang.IllegalThreadStateException
     at java.lang.Thread.setDaemon(Thread.java:1367)
     at com.threads.DeamonThreads.main(DeamonThreads.java:8)

The main thread cannot be set as daemon thread. Because a thread can be set daemon before its running and as soon as the program starts the main thread starts running and hence cannot be set as daemon thread.

As given in javadocs...

public final void setDaemon(boolean on)

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 invoked before the thread is started.

Parameters: on - if true , marks this thread as a daemon thread

Throws:

  • IllegalThreadStateException - if this thread is alive

  • SecurityException - if checkAccess() determines that the current thread cannot modify this thread.

As others already have pointed out, you can not do that, but what is the real problem that you want to solve?

There is nothing special about the main thread, so why not get rid of it? Would this work for you?

public static void main(String[] args) {
    ...create at least one non-daemon thread...
    Thread t = new Thread(() -> {
        daemon_main(args);
    });
    t.setDaemon(true);
    t.start();
}

public static void daemon_main(String[] args) {
    ...do whatever else main() did...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM