This site javatpoint is very useful for programming languages like JAVA,PYTHON,C,C++, Data Structures etc.Java learning Concept also provides technical materials , which are related to latest technologies. We provides very easy lectures to our viewers from beginning to advance level.We focus logical content instead of theoretical content.

Wednesday, 6 June 2018

DAEMON THREADS IN JAVA

Daemon Threads:

The Threads which are executing in side the background are called daemon threads in java.
ex:garbage collector,signal dispatcher etc.
The main objective of daemon threads is ,it provide support of non_daemon threads .
we can check daemon nature by using isDaemon() method of Thread class .
Syntax:
               public boolean  isDaemon()
we can change daemon nature of thread by using setDaemon() method of thread class.
Syntax:
public void setDaemon(boolean  b)

we can change Thread  nature before starts threads,we can't change thread nature after starts threads .if we trying to  change then we will get run time exception ILLIGELTHREADSTSTEEXECPTION

Default Threads: By default  main thread is a non-daemon and for all remain threads are inherit by parent to child class.that means it depends on main thread if main thread is non-daemon then child thread is also non-daemon and if parent thread is daemon  then child thread is also daemon.

Example

class Dthread extends Thread

{
pblic void run()
{

if(Thread.currentThread().isDaemon())
{
System.out.println(Thread.currentThread.getName());
System.out.println( "is a Daemon Thread");
}
else
{
System.out.println(Thread.currentThread.getName());
System.out.println( "is a user Thread");
}
}
}
class DemonThreads
{
public static void main(String[] args)
{

dThread dt1=new dThread();
dThread dt2=new dThread();
dt1.setDaemon(true);
dt1.start();
dt2.start();


}

}

output:

Thread-0 is a Daemon Thread 
Thread-1 is a non-daemon athread





Adbox