< Prev
Next >



Creating a Thread






Two ways to create a Thread :







Constructors of Thread class when extending a Thread class.







The importance of run() method of Thread class and Runnable interface







How can we start a new Thread?


In order to start a newly created thread, we must call start() method of Thread class, which will eventually call the run() method of Thread class, to run the new thread.




Creating a thread by extending Thread class and overriding its run() method.


We are going to create a new thread by extending the Thread class and overriding its run() method. This new thread will exit when the overridden run() method finishes its execution.
class ThreadExm extends Thread	//Extending the Thread class
{
ThreadExm(String name) //Constructor
{
super(name);	       //Calling superclass Thread's constructor
}


public void run() //Entry Point of the new thread.
{
System.out.println("Name of non-main thread - " + getName()); //Getting the name of this new thread.

try
{
	System.out.println(getName()+ " is going to sleep for 3 seconds");
	Thread.sleep(3000);
	System.out.println(getName()+ " awakened and exits"); 
}
catch(InterruptedException e)
{
	System.out.println(e);
}

}// run method defintion ends


public static void main(String... ar)
{
ThreadExm newTh = new ThreadExm("newThread");
newTh.start(); //starting the new thread, calls run() method automatically
}

}


Output is -:


Name of non-main thread - New Thread
New Thread is going to sleep for 3 seconds
New Thread awakened and exits


Program Analysis







Creating a thread by implementing Runnable interface.


We are going to create a user defined thread by implementing Runnable interface and implementing its run() method.
class ThreadRun implements Runnable
{

public void run()
{
Thread t= Thread.currentThread();
System.out.println("Name of this thread - "+ t.getName()); //Getting the name of this new thread.

try
{
	System.out.println(t.getName()+ " is going to sleep for 3 seconds");
	Thread.sleep(3000);
	System.out.println(t.getName()+ " awakened and exits"); 
}
catch(InterruptedException e)
{
	System.out.println(e);
}
}


public static void main(String... ar)
{
ThreadRun newTh = new ThreadRun();
Thread th= new Thread(newThread,"New Thread"); //Calling Thread's constructor & passing the object
					       //of Runnable interface implementer  & the name of thread.
							
th.start(); /starting the new thread, calls run() method automatically
}

}


Output is -


Name of non-main thread - New Thread
New Thread is going to sleep for 3 seconds
New Thread awakened and exits


Program Analysis





Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< Lifecycle of a Thread
Thread Priorities>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2