Multithreading in Java

Multithreading in java is the most important topic in java. In this post, we will discuss the Multithreading in java example, and we will try to cover the real time example of multithreading in java.  

Here is the table content of the article will we will cover this topic.
1. Process and Thread in java?
2. What is multithreading in Java?
3. Important points about multithreading?
4. How does the thread in java work Or Define a thread in java?
5. Advantages of multithreading in Java?

6. What is thread in java?
7. Properties of thread in java?
8. Creation of thread using thread class?
i) Creation of thread by extending thread class in java?
ii) Creation of thread by anonymous class?

9. Creation of thread using Runnable interface?
i) Creation of thread by implementing Runnable interface in java?
ii) Creation of thread by anonymous class?

10. Creating multiple threads in java?
11. Memory representation of thread creation in java?
12. How do multiple threads work?
13. How does thread work if an exception occurs?
14. start() and run() method?
15. How does the start() method work?
16. If we run() method called instead of start() method?
17. What is the main thread in java?
18. Important points about the main thread?

19. Thread life cycle in java?

Process and Thread in java

Before understanding the concept of multithreading in java, we need to understand the concept of thread in java and process. After that, we will see the multithreading program in java.

Process: The execution of the program is referred to as the process. On another hand, we can say when we are executing a program it means a process is in running. A program can be divided into small processes(subprocesses) also.

Thread: A thread is the smallest unit of process or a lightweight sub-process. A program can have any number of sub-processes and each sub-process can run parallelly by a thread. A thread behaves like a separate CPU executing the process, but the CPU shares the time between threads. Each program has at least one thread. If we create a simple program to print “Hello world”, it means at least one thread will exist in the program. We will discuss it later in detail.

public class MainClass 
{
    public static void main (String [] args) 
    {
    	System.out.println("Hello world");
    	System.out.println("Thread name : "+Thread.currentThread().getName());
    }
}

Output: Hello world
Thread name : main

What is multithreading in Java?

When a process is executed by multiple threads simultaneously is known as multithreading in java. As we know a process can have a number of subprocesses and each subprocess can be executed in parallel by threads. An application can have any number of processes. Each process can be assigned to a single thread or multiple threads.

OR

Multithreading in java is a process, in which two or more threads can run the process and do the maximum utilization of the CPU. It is also known as Concurrency in Java. Each thread can run in parallel with the other.
Java supports multithreading, which means we can develop a program that can have two or more parts (sub-processes) that can run concurrently and each part(subprocess) can have a different task. By the use of multithreading, we can do maximum optimization of the CPU.

Multithreading in Java

Important points about multithreading in Java

1. Multithreading is used to utilize the maximum time of the CPU. In multithreading, we can execute two or more parts of a program simultaneously. Each part of the program can run separately by single or multiple threads.

2. A Thread is a lightweight sub-process, that can separate from other threads. The multiple threads can share a common memory space. The CPU divides the time for all thread and switch from one thread to another thread for a while.

3. A thread runs independently because it has a separate path of execution.

How does the thread in java work Or Define a thread in java?

As we already discussed thread is the lightweight and smallest part of the process. A process can have one or more threads. Each process has at least one thread. To complete a process, the subprocesses(thread) can work independently and provide better performance. Multithreading means you can have multiple threads of execution inside the same program. If you have a number of threads that are executing the same program, It behaves like having multiple CPUs execute the same program.

Multithreading in Java

Advantages of multithreading in Java

Before moving further, we should learn what is the advantages of multithreading and why it is so popular.

Maximum utilization of a single CPU.

As we know CPU is much faster than other resources like network, and I/O operations. Multithreading is to be able to better utilization the CPU. Let’s see the multithreading in java example.

Suppose the CPU has only a single process that is handled by a single thread. The thread is waiting for the response from the I/O operation meanwhile the CPU is in the ideal state because it has not any other thread to process.
In multithreading, multiple threads can work parallelly so if one thread is waiting for any resource then another thread could use the CPU.

Give fast response

By use of multithreading, we can provide a fast response to the users that makes a better experience. Suppose we are using multithreading in our application. The user submits the form by clicking on a button, by use of one thread, we will submit the form on the network and wait for a response meanwhile another thread can show a loading icon on the screen that gives the user a better experience.

Better user experience

Suppose we are receiving requests from many clients and processing them. If we are using one thread for processing then we can’t do response faster because there may be requests that take a long time to process. Then all other clients would wait until that one request has finished. This type of situation can get frustrate the clients. But if we will use multiple threads then we can handle multiple requests at the same time.

What is the thread in java?

thread is a part(subprocess) of a program that can execute independently. In java multiple threads can run concurrently within a program. A process can run by multiple threads, each thread can run independently and work concurrently. Each program has at least one thread that is called the main thread. The main thread starts from the beginning of the main method and ends when the main method is executed completely. Each thread is created after the main thread because JVM starts from the main thread. A program can have any number of threads and each thread has a priority number that helps the JVM to prioritize the threads.

Let’s take a java thread example that is a real-time example of multithreading in java. Suppose an example of a website that has a number of pages. Multiple clients can make a number of requests at the same time and the web server returns different pages on each request. It means the web server application may have multiple threads that are running the multiple requests of the client. The application has multiple processes and each process may have a subprocess that is handled by a particular thread.

Thread in java

Let’s take an example of thread in java

Let’s discuss the thread program in java. How does thread work and how we can use it? There are two ways to create a thread in java. We can create by Thread class or Runnable interface. We can read the creation of thread in java. Every program has at least one thread that is automatically created by JVM. Let’s see the thread program in java.

public class ThreadExample implements Runnable  
{
	public static void main(String arg[])
	{
		System.out.println("Main method");
		System.out.println("The main thread is running :"+Thread.currentThread().getName());
		ThreadExample obj = new ThreadExample();
		Thread t1 = new Thread(obj);
		t1.start();
	}

	@Override
	public void run() 
	{
		System.out.println("Thread is running..."+Thread.currentThread().getName());
	}
}

Output: Main method
The main thread is running :main
Thread is running…Thread-0

In the above example, we are creating a thread by use of Runnable interface. We will discuss later, how to create a thread by Runnable interface. As of now, we will focus on this example.
When JVM enters the main method, it creates a thread automatically that is called the main thread. you must be noticed the main thread is automatically created by JVM. In the next line, we are creating a thread t1 and starting the execution of thread t1 by start() method.

Thread in java

Properties of thread

Each thread has some common properties that help the JVM to execute them and use these properties to predict the thread.

1. Lightweight process: A thread is a lightweight process in a program. A program can have any number of sub-processes that are handled by threads. That’s why we call the thread a lightweight process.

2. Sharing resources: Multiple threads can share resources like data and code. A thread can make a change in data that are used by another thread. Even this concept leads to the duplicity of data. We will discuss it later.

3.  At least one thread: Each program has at least one thread. Whenever we create a program the JVM automatically creates a thread. A program can contain any number of threads.

4. Thread priority:  Each thread has a priority that lies between 1 to 10. The JVM automatically assigns the priority to each thread but we can do it by setPriorty() method. The default priority of a thread is 5.  The JVM executes the higher priority thread before the lower priority. If two thread has the same priority the thread scheduler decides which thread run first.

5. Creation of thread: A thread can create in two ways either by Thread class or Runnable interface.
We can create a thread by extending the Thread class or by implements the Runnable interface. The Thread class provides some methods and constructors that can be used to perform operations. We can learn it in detail.

6. Types of the thread: In java, we can create types of thread: user threads or daemon threads. The user thread has a higher priority than the daemon thread. A daemon thread always works in the background and JVM can ignore them before terminating the process. But for the user thread, the JVM could not terminate the execution before the completion of the user thread. Memory management, system management, and signal processing are managed by daemon threads.

7. Life cycle of thread

A thread goes in different states during the execution of the program. It has 6 states those are:

1. New state
2. Runnable state
3. Running state(This state doesn’t exist)
4. Blocked state
5. Waiting state
6. Timed waiting
7. Terminated state 

8. Thread scheduler: The execution of the thread totally depends on the thread scheduler. A thread scheduler decides which thread should be run first. The thread scheduler depends upon the JVM. The JVM can indicate to the thread scheduler those threads are more important or critical.

9. Stack: Each thread stores the local variables and method call in its own stack. The size of this stack depends on the JVM and it can be controlled using -XX:ThreadStackSize JVM option.

How to create a thread in java

We have seen what is the thread in java and java thread example.Now, we will see What is the creation of thread in java. There are two ways to create a java thread by extends the Thread class or implements the Runnable interface. But how does a thread work in memory and how it starts the execution separately?

There are two ways to create a thread in java. We can create a thread by use of the Thread class or Runnable interface. But the Creation of a thread in java is always dependent upon the situation and the scenarios. In both ways, we provide the body of the thread in the run() method and start the execution of the thread by the start() method. Let’s discuss how to create a thread in java in different ways:

1. Creation of thread using thread class

We can create a thread in java by using the Thread class. Also, we have two ways to create a thread: We can create a thread by extending the Thread class or by use of the anonymous class.

Creation of thread by extending thread class in java

We can create a thread by extending the Thread class that exists in java.lang package. As a result, We need to extend the Thread class, in our class, and create an object/instance of that class. So, We must override the run() method that is present in the Thread class.

Step 1: Create a class in which you want to create a new thread.

Step 2: Extend the Thread class by extends the keyword.

In Step 3: Override the run() method of the Thread class and provide the body to run() method. Finally, The body of the run() method is considered the body of the thread that we want to create.

Step 4: Create the object of the class.

Step 5: Call the start() method to run the execution of the thread.

public class MyThread extends Thread
{
	public static void main(String[] args) 
	{
		MyThread thread1 = new MyThread();
		thread1.start();
	}
	@Override
	public void run()
	{
		System.out.println("My thread is running");
	}	
}

Output: My thread is running

Explanation of the above example

Step 1: Here we are creating MyThread class. In which we want to create the thread.

Step 2: Extending the Thread class in MyThread class by extends the keyword. After extending the Thread class, now all the methods of the Thread class are present in MyThread class. 

Step 3: In this step, we are overriding the run() method of the Thread class. Overriding, the run() method means we are providing the body to the thread. So, The code present in the run() method executes separately.

Step 4: Creating the object of the MyThread class. It means we are creating the object of the thread and now the thread is in a NEW state. We will discuss it lifecycle of the thread.

Step 5: Now thread has been created we just need to start the execution of the thread. To start the execution of the thread we are calling the start() method that is present in the Thread class. Finally, The start() method automatically calls the run() method of the current class. We will discuss it later in detail.

Creation of thread by anonymous class

If you are not familiar with the anonymous class in java. Please read it first.

We can create a thread by using of anonymous class in our class. Hence, Here we don’t need to extend the Thread class in our class. We will give the implementation to run method by use of the anonymous class. As we are not inheriting the Thread class, so it means only methods of Thread class will not be available in our class.

Step 1: Create a class in which you want to create a new thread.

Step 2: Create an object of the Thread class by use of a constructor and also provide the body to the run() method. That will be considered an anonymous class.

Step 3:  Call the start() method to run the execution of the thread.

public class MyThread
{
	public static void main(String[] args) 
	{
		Thread thread = new Thread()
		{
			public void run()
			{
				System.out.println("My thread is running");
			}
		};
		thread.start();
	}
}

Output: My thread is running

Explanation of the above example

Step 1: Here we are creating MyThread class. In which we want to create the thread.

Step 2: Create an anonymous class and override the run() method. Here we are providing the body of the thread.

Step 3: Create the object of the Thread class through an anonymous class. So, It means we create an object of thread and now the thread is in a NEW state. Similarly, We will discuss it lifecycle of the thread.

Step 4: Now thread has been created we just need to start the execution of the thread. Also, To start the execution of the thread we are calling the start() method that is present in the Thread class. The start() method automatically calls the run() method of the current class. We will discuss it later in detail.

2. Creation of thread using Runnable interface

Another way to create a thread is by implementing the Runnable interface. Here we have two ways to create the thread through the Runnable interface. We can create a thread by implements the Runnable interface or by use of the anonymous class.

Creation of thread by implementing Runnable interface in java

We can create a thread by implementing the Runnable interface that exists in java.lang package. We need to implement the Runnable interface, in our class. The Runnable interface has only one method which is the run() method. In conclusion, We must provide the body with the run() method.

Step 1: Create a class in which you want to create a new thread.

Step 2: Implement the Runnable interface by implements keywords.

Next, Step 3: Provide the body to the run() method of Runnable. The body of the run() method is considered the body of the thread that we want to create.

Step 4: Create the object of the class that implements the Runnable interface.

Step 5: Create an object of the Thread class by use of a constructor that takes the object of Runnable types as a parameter. For eg: new Thread(Runnable target)

Step 6: Use the thread object to call the start() method to run the execution of the thread.

public class MyThread implements Runnable 
{
	public static void main(String[] args) 
	{
		MyThread obj = new MyThread();
		Thread thread1 = new Thread(obj);
		thread1.start();
	}

	@Override
	public void run() 
	{
		System.out.println("My thread is running");	
	}
}

Output: My thread is running

Explanation of the above example

Step 1: Here we are creating MyThread class. In which we want to create the thread.

Step 2: Implementing the Runnable interface in MyThread class by implements keyword. While Implementing the Runnable interface, we need to implement the run() method in MyThread class.

Step 3: In this step, we are providing the body to the run() method. By implementing the run() method means we are providing the body to the thread. Therefore, The code present in the run() method executes separately.

Step 4: Create the object of MyThread class that is implementing the Runnable interface.

Step 5: Create the object of the Thread class and pass the object of MyThread in the constructor of the Thread class. Because it takes the object of the Runnable interface.

Step 6: Now thread has been created we just need to start the execution of the thread. Similarly, To start the execution of the thread we are calling the start() method that is present in the Thread class. Hence, The start() method automatically calls the run() method of the current class. We will discuss it later in detail.

Creation of thread by anonymous class

If you are not familiar with the anonymous class in java. Please read it first.

We can create a thread by using of anonymous class in our class. In conclusion, we don’t need to implement the Runnable interface in our class. We will give the implementation to run method by use of the anonymous class.

Step 1: Create a class in which you want to create a new thread.

Step 2: Create an object of the Runnable interface by providing the anonymous implementation of the interface. Another is, Provide a body to the run() method and which will be considered an anonymous class.

Step 3: Create an object of the Thread class and pass the object of Runnable in the constructor of the Thread class.

Step 4:  Call the start() method to run the execution of the thread.

public class MyThread 
{
	public static void main(String[] args) 
	{
		Runnable runnable = new Runnable() 
		{
			@Override
			public void run() 
			{
				System.out.println("My thread is running");
			}
		};
		Thread thread1 = new Thread(runnable);
		thread1.start();
	}
}

Output: My thread is running

Creation of thread by anonymous class(Lambda expression)

Please read the functional interface and lambda expression first.

As we know the Runnable interface is a functional interface because it has only one method. So, we can use the lambda expression to implement it. By use of lambda expression, we can reduce the code and make it more readable.

public class MyThread 
{
	public static void main(String[] args) 
	{
		Runnable runnable = () -> System.out.println("My thread is running");
		Thread thread1 = new Thread(runnable);
		thread1.start();
	}
}

Output: My thread is running

Creating multiple threads in java

We can create multiple threads in the java program. So, Let’s see how to create multiple threads in java.

class MyThread implements Runnable 
{
	String name;
	Thread thread;
	MyThread(String threadName)
    {
	    name = threadName; 
	    thread = new Thread(this, name);
	    thread.start();
    }
	public void run() 
	{
		 try 
		 {
		     for(int i = 0; i < 5; i++) 
		     {
		    	 System.out.println("The "+ name + " is running...");
		    	 Thread.sleep(1000);
		     }
		 }
		 catch (InterruptedException e) 
		 {
			 System.out.println(name + "Interrupted");
		 }
	}
}
 
public class MultipleThread 
{
	public static void main(String args[]) 
	{
	     new MyThread("First thread");
	     new MyThread("Second thread");
	     new MyThread("Third thread");
	     try 
	     {
	    	 Thread.sleep(10000);
	     } 
	     catch (InterruptedException e) 
	     {
	    	 System.out.println("Main thread Interrupted");
	     }
	 }
}

Output: The First thread is running…
The Third thread is running…
The Second thread is running…
The Third thread is running…
The Second thread is running…
The First thread is running…
The First thread is running…
The Second thread is running…
The Third thread is running…
The Third thread is running…
The First thread is running…
The Second thread is running…
The First thread is running…
The Second thread is running…
The Third thread is running…

Explanation of example

NOTE: The output of the above program can vary because we can’t predict the output of multiple threads if they are running parallel.  In the above example, you have seen we are creating a class MyThread that implements the Runnable interface and also provides the body to run() method.

Line 1: Here we are creating the MyThread class that implements the Runnable interface.

Line 5: Creating the constructor of MyThread that is used to create a new thread.

Also, Line 7: Assigning the name of the thread.

Line 8: Creating a new thread and providing the name of the thread.

Line 9: To start the execution of the thread call the start() method.

Another in Line 11: Here we are providing the body to run() method.

Line 15-19: The thread will execute the statement written on line 17. After that the thread will go to sleep for 1 second, meanwhile, another thread will enter the loop and execute the statement, and so on.  

Line 28: We are creating another class that is used to invoke the constructor of the MyThread class.

Line 32 – 34:  Here we are calling the constructor of the MyThread class and providing the names of threads.

how to create multiple thread in java

6 thoughts on “Multithreading in Java”

Leave a Comment