Home » Java Thread setDaemon() Method with Examples

Java Thread setDaemon() Method with Examples

by Online Tutorials Library

Java Thread setDaemon() method

The setDaemon() method of thread class is used to mark the thread either daemon thread or a user thread. Its life depends on the user threads i.e. when all user threads die, JVM terminates this thread automatically. It must be invoked before the thread is started.

If you call the setDaemon() method after stating of the thread, this method will throw IllegalThreadStateException.

Syntax

Parameter

on: If true, marks the thread as a daemon thread.

Return

This method will return true if the thread is daemon thread otherwise return false.

Exception

IllegalThreadStateException: If the thread is alive.

SecurityException: If the current thread cannot modify the thread.

Example 1

Test it Now

Output:

daemon thread work  daemon thread work  user thread work  

Example 2

When you call the setDaemon() method after starting of thread.

Test it Now

Output:

Name of thread: Thread-0  Daemon: false  Exception in thread "main" java.lang.IllegalThreadStateException  at java.lang.Thread.setDaemon(Thread.java:1359)  at JavaSetDaemonExp2.main(JavaSetDaemonExp2.java:17)  

You may also like