Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Multithreading. No Comments on Creating Threads
0
(0)

In this article we will look at creating threads, a single thread and multiple threads using Thread class and Runnable interface along with sample programs.

 

We can create a thread in a Java program in two ways, either by:

  1. Extending Thread class or
  2. Implementing Runnable interface

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


Creating a Single Thread

 

Implementing Runnable Interface

 

Following are the steps that must be performed for creating a thread using Runnable interface.

  1. Create a class and implement Runnable interface.
  2. Implement run() method. This method contains the thread code and is the entry point for every thread.
  3. Invoke start() method. This method calls the run() method.

 

Below is a program which creates a single thread using Runnable interface:

class MyThread implements Runnable
{
	MyThread()
	{
		Thread t = new Thread(this);
		System.out.println("Child thread: " + t);
		t.start();
	}

	@Override
	public void run()
	{
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println("Child thread: " + i);
				Thread.sleep(500);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("Child thread is interrupted!");
		}
		System.out.println("Child thread terminated");
	}
}

public class Driver
{	
	public static void main(String[] args)
	{
		new MyThread();
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println("Main thread: " + i);
				Thread.sleep(1000);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("Main thread is interrupted!");
		}
		System.out.println("Main thread terminated");
	}
}

 

Output of the above program is:

Child thread: Thread[Thread-0,5,main]
Main thread: 1
Child thread: 1
Child thread: 2
Main thread: 2
Child thread: 3
Child thread terminated
Main thread: 3
Main thread terminated

 

Extending Thread Class

 

Following are the steps that must be performed for creating a thread using Thread class:

  1. Create a class and extend Thread class.
  2. Override the run() method.
  3. Invoke start() method.

 

Below is a program which creates a single thread using Thread class:

class MyThread extends Thread
{
	MyThread()
	{
		super(); //Optional
		System.out.println("Child thread: " + this);
		start();
	}

	@Override
	public void run()
	{
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println("Child thread: " + i);
				Thread.sleep(500);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("Child thread is interrupted!");
		}
		System.out.println("Child thread terminated");
	}
}

public class Driver
{	
	public static void main(String[] args)
	{
		new MyThread();
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println("Main thread: " + i);
				Thread.sleep(1000);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("Main thread is interrupted!");
		}
		System.out.println("Main thread terminated");
	}
}

 

Output of the above program:

Child thread: Thread[Thread-0,5,main]
Main thread: 1
Child thread: 1
Child thread: 2
Child thread: 3
Main thread: 2
Child thread terminated
Main thread: 3
Main thread terminated

 

Note: Output for the above example programs might vary a little when you run the above code on your machine as which thread executes when is under the control of JVM.

 

Creating Multiple Threads

 

As we already know how to create a single thread, you can create multiple threads by simply creating multiple objects of your thread class as shown in the example program below:

class MyThread implements Runnable
{
	Thread t;
	MyThread(String name)
	{
		t = new Thread(this, name);
		System.out.println("Child thread: " + t);
		t.start();
	}

	@Override
	public void run()
	{
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println(t.getName() + ": " + i);
				Thread.sleep(500);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println(t.getName() + " is interrupted!");
		}
		System.out.println(t.getName() + " is terminated");
	}
}

public class Driver
{	
	public static void main(String[] args)
	{
		new MyThread("First Thread");
		new MyThread("Second Thread");
		new MyThread("Third Thread");
		try
		{
			for(int i = 1; i <= 3; i++)
			{
				System.out.println("Main thread: " + i);
				Thread.sleep(1000);
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("Main thread is interrupted!");
		}
		System.out.println("Main thread terminated");
	}
}

 

Output of the above program is:

Child thread: Thread[First Thread,5,main]
Child thread: Thread[Second Thread,5,main]
First Thread: 1
Child thread: Thread[Third Thread,5,main]
Second Thread: 1
Main thread: 1
Third Thread: 1
First Thread: 2
Second Thread: 2
Third Thread: 2
First Thread: 3
Second Thread: 3
Main thread: 2
Third Thread: 3
First Threadis terminated
Second Threadis terminated
Third Threadis terminated
Main thread: 3
Main thread terminated

 

How to choose between Thread and Runnable?

 

You may think that why Java is providing two options (Thread class and Runnable interface) for creating threads? Choose Thread class when you want to override some of the methods available in the Thread class.

 

Choose Runnable interface if you don’t want to override any methods or if your class have to extend some other class (multiple inheritance of classes is not supported).

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *