Thread life cycle in java

Previous
Next

Multi threaded application:

  • Define and execute a Custom thread along with Default thread.
  • When multiple threads are executing, any thread can completes execution first.
  • Application ends only when all the threads moved to dead state.

Life cycle of a thread:

  • As a programmer, we need to define Custom thread either extending Thread class or implementing Runnable interface.
  • We need to override run() method to specify the thread logic.
  • Once Thread class is ready, we need to instantiate the class.

start():

  • A pre-defined method belongs to Thread class.
  • When we invoke start() method, it allocates separate memory to execute thread logic(run method logic) parallel.

Code program:

class Custom extends Thread
{
	public void run()
	{
		for (int i=1 ; i<=50 ; i++)
		{
			System.out.println("i value is : " + i);
		}
	}
}
class Default 
{
	public static void main(String[] args) 
	{
		Custom th = new Custom();
		th.start();
		
		for (int j=1 ; j<=50 ; j++)
		{
			System.out.println("j value is : " + j);
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form