Thursday, June 16, 2016

Daemon Thread and Thread Life Cycle example java

Daemon Threads

Sometimes, a thread has to continuously execute without any interruption to provide service to other threads.Such threads are called Daemon Threads.for example---oracle.exe is a program that runs continuously in a computer.

A daemon thread is a thread that executes continuously.Daemon threads are service providers for other threads or objects.It generally provides a background processing.

To make  a thread t as daemon thread,we can use setDaemon() method as:
 t.setDaemon(true);

To know if a thread is daemon or not,isDaemon() useful.
boolean x=t.isDaemon();

If  isDaemon() returns true then the thread t is a Daemon Thread,otherwise not.

Thread Life Cycle:

Starts from birth of a thread till its death, a thread exists in different states which are collectively called Thread Life Cycle.

A thread will be born when it is created using Thread Class as:

Thread t=new Thread();

Then thread goes into runnable state when start() method is called. Yeild() method may pause a thread bu the thread will be still in running state only.
A thread can go to runnable state to non-runnable state,when sleep() or wait() method acts on it.
Finally, a thread is terminated from memory only when it comes out of run() method.This happens when the thread complete its execution of run() method  and naturally comes out of it or when user force it to come out of it.

(start()---------->runnable(yeild()------->sleep()or wait()------Dead)
New Thread-->Runnable-->Non Runnable--->Dead



No comments: