Androidberry logo Androidberry text logo
AndroidBerry Home
  • Learn Java
  • Java Programs
  • Interview Questions
  • Androidberry facebook
  • Androidberry twitter
  • Androidberry google plus

Java Tutorials


Basic Introduction

Decision Making

Looping

Classes and Objects

Inheritance

Interface

Packages

Exception Handling

Introduction of Errors
Java Exceptions
Java Try Block
Java Catch Block
Java Finally Block
Java Throw Keyword
Java Throws Keyword
Java Builtin Exceptions
User Defined Exceptions

Multithreading

Java Multithreading
Creating a Thread
Thread Life Cycle
Thread Exceptions
Thread Synchronization

Java Applets

What is Applet?
Java Applet vs Application
Creating a Applet
Displaying Applet on Webpage
Applet Lifecycle
Applet Tag
Passing Parameters to Applet
Setting Color to applet
Update and Repaint method
Using Fonts in Applet

Graphics Programming

More on Java

Java Programs
Java Keywords Dictionary
Java Interview Questions

Java Thread Lifecycle


Lifecycle of thread is nothing but the lifetime of thread.

During lifecycle, thread enters into 5 different states to complete it's task.

Thread States

From start to end there are total 5 states of thread as

  1. Newborn state
  2. Runnable state
  3. Running state
  4. Blocked state
  5. Dead state

1. Newborn State

When a thread object is created, then the thread is said to be in Newborn state.

In this state, the thread is just created but not scheduled for the cpu execution.

Newborn thread can be either

  1. Scheduled for running in the cpu by calling start () method.
  2. Kill the thread by directly calling stop() method .

Remember : When we call the start () method then the thread is scheduled for execution. If cpu is currently busy then thread comes in the Runnable state to wait for allocation otherwised directly jumps into the Running state.

2. Runnable State

The runnable state indicated that the thread is almost ready for the execution and waiting for the cpu allocation.

In this state the Threads are placed in queue in First In First Out (FIFO) manner.

Here, Thread priorities are also considered while executing them. If the thread has highest priority then it is moved into the Running state directly. If threads have same priority then they are executed by giving a time slice using algorithm like round robin.

3. Running State

The running state is the actual state in which the thread is executing its task.

Thread continues to execute in running state untill the highest priority process comes.

Thread is released by 3 conditions

1. Suspeding a thread

  • Running thread is suspended by calling the suspend() method of thread.
  • Suspend() method is useful when we want to stop a thread for some time but not for the all time.
  • Thread can be restarted when suspended by calling a resume () method.

2. Sleeping a thread

  • Running thread is moved to the sleeping (idle) process for specific period of time in milliseconds by calling sleep(time) method.
  • The thread is added into the queue and waits until the time ends.
  • As soon as the time period is over the thread is re-entered in runnable state and then into running state.
  • Sleep method is always written inside the try block otherwised it fetches an exception.

3. Waiting a thread

  • Running thread waits until some event occurs and wait() method is used to wait for the condition.
  • notify () method is used to schedule the thread to run again.

4. Blocked State

Thread in blocked state is not actually dead. It can be reschedules for later execution.

The thread comes into the blocked state when following either of 3 methods is get called.

Sr.no Blocked by method Re-schedules by method
1. suspend () resume ()
2. wait () notify ()
3. sleep () -

5. Dead State

The thread is moved into the dead state when it has completed the execution or terminated by some reasons.

We can terminate the thread by calling stop () method of thread class.

Thread's stop () method can be called from :

  1. Newborn state
  2. Running state
  3. Blocked state

Methods of Thread class

Sr.no Method Name Description
1. void start () This method start the thread and executes run () of thread.
2. void run () This method contains the actual code of the thread which is executed.
3. void setName (String) This method changes the name of the Thread object. Name is displayed by calling getName() method.
4. void setPriority () This method sets the priority of the Thread object. Priorities are between 1 to 10.
5. void setDaemon (boolean on) This method indicates the thread is a daemon thread by passing true.
6. void join () The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or by passing milliseconds.
7. void interrupt () This method interrupts the thread,causing it to continue its execution if it was blocked for any reason.
8. boolean isAlive () This method returns true if the thread is alive.

Static methods of thread class.

Following methods are used to perform operations on curretly running thread.

Sr.no Method Name Description
1. void yield () This method causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
2. void sleep (long) This method causes the currently running thread to block for at least the specified number of milliseconds.
3. boolean holdsLock(Object) This method returns true if the current thread to block for at least the specified number of milliseconds.
4. Thread currentThread() This method returns a refference to the currently running thread, which is the thread that invokes this method.
5. void dumpStack () This method prints the stack trace for teh currently running thread, which is useful when debugging a multithreaded application.

Example of Thread

class A extends Thread
{
    public void run()
    {
	System.out.println("Thread A started");
	for(int i=1;i<=5;i++)
	{
	    yield();
	    System.out.println("A : "+i);
	}
			
	System.out.println("Thread A exited");
    }
}
class B extends Thread
{
    public void run()
    {
	System.out.println("Thread B started");
	for(int i=1;i<=5;i++)
	{
	    System.out.println("B : "+i);
	    if(i==3) stop();
	}
			
	System.out.println("Thread B exited");
    }
}
class C extends Thread
{
    public void run()
    {
	System.out.println("Thread C started");
	for(int i=1;i<=5;i++)
	{
	    System.out.println("C : "+i);
	    if(i==1)
	    {
		try
		{
		  sleep(200);
		}
		catch(Exception e) { }
	    }
	 }
			
	System.out.println("Thread C exited");
    }
}
public class Test {
	public static void main(String[] args) 
        {
		
	   A a1 = new A();
	   B b1 = new B();
	   C c1 = new C();
	   a1.start();
	   b1.start();
	   c1.start();
	}
}

Output

Thread B started
Thread C started
Thread A started
C : 1
B : 1
A : 1
B : 2
A : 2
B : 3
A : 3
A : 4
A : 5
Thread A exited
C : 2
C : 3
C : 4
C : 5
Thread C exited

In above example we have created 3 seperate threads by extending thread class. We have also used different methods of thread class.


<< Previous Next >>

See Also

All Java Programs
Java Keywords
Java Interview Questions

AndroidBerry Support

About us
Contact us
Suggest us
Questions?

Follow us

Androidberry FacebookFacebook
Androidberry TwitterTwitter
Androidberry GooglePlusGoogle+
Back to top
Androidberry Name Logo