Main Thread in Java | Use of Thread

What is Thread in Java?


A thread in Java simply represents a single independent path of execution of a group of statements. When we write a group of statements in a program, these statements are executed by JVM one by one. This execution process is called thread in Java.

There is always at least one thread running internally in every program and this thread is used by JVM to execute statements in the program.

We can also create more than one execution thread in a program that can be used to perform multiple tasks simultaneously.

When we create more than one thread in a program, each thread has its own path of execution and all the threads share the same memory address space, data, and code in a program.

What is Process in Java? 


Thread in Java is the smallest unit of executable code in a program. It helps to divide a program into multiple parts to speed up the process. A process is a program that executes as a single thread. In other words, when an executable program is loaded into memory, it is called process.

Points to be Noted:

1. Every individual process has its own separate memory address space and can execute a different program.


2. Each process can have more than one thread.

3. Each process communicates through the operating system, files, and network.

When we will create a new thread in a program, it shares the same memory address space with other threads in a program whereas every individual process has its own separate memory address space. Therefore, creating a thread takes fewer resources than creating a new process. Look at the below figure to understand better.

Thread in Java

As you can see in the above figure, the thread is executed inside a process and one process can have also multiple threads. There can be multiple processes inside the operating system.

Multiple Threads are independent of each other. At a time only one thread is executed. If an exception occurs in one thread, it doesn’t affect other threads.

Why Java threads are lightweight process?


Java Threads are also known as light-weight processes which means that they can be executed in the same memory space because all the threads in the main application program share the same address space in the memory so that they can easily communicate among themselves. Thus, they also take less space in memory and less processor time. 

Main Thread in Java


Every Java program has always at least one thread, even if you do not create any thread. This thread is called main thread. The main thread is also called parent thread and the rest of threads that are generated from it are called child threads of the program.

Main thread is the last thread to be executed in a program. When main thread finishes the execution, the program terminates immediately. Whenever Java program starts, main thread is created automatically.

This main thread is available in all programs. We can control the execution of the main thread by creating a Thread object and then using methods of Thread class.

To do so, we will have to create a Thread object by calling currentThread() method of class Thread. A Thread object can be created as follows:

Thread obj = Thread.currentThread();

Since currentThread() method of class Thread is a public static method, therefore, we can call it using class name.

The currentThread() method returns a reference of current thread on which it is called. “obj” is a reference variable that is assigned to store the return value of currentThread() method.

Let’s create a program to find the thread used by JVM to execute statements and display the name of main thread.

Program source code 1:

public class MainThread 
{
public static void main(String[] args) 
{
// Create a Thread object by calling currentThread() method of class Thread.
   Thread obj = Thread.currentThread();
   
   System.out.println("Current thread is " +obj);
   System.out.println("Name of current thread is " +obj.getName());
  }
}
Output:
      Current thread is Thread[main,5,main]
      Name of current thread is main

Explanation:

1. In this program, currentThread() is a static method in a class Thread. Therefore, we called it as Thread.currentThread(). This method returns the reference of main thread because this is called inside the main thread. The reference of main thread will be stored in a variable obj of type Thread.

2. When line 8 will be executed by JVM, it will display an output “Thread[main,5,main]” on screen. In the square bracket, the first value, main represents the name of thread; second value 5 represents the priority of main thread.

Every thread will have a priority number associated with it that can be range from 1 to 10. 1 is the minimum priority and 10 is the maximum priority of a thread.

The third value main represents the name of group to which main thread belongs.

3. getName() method of Thread class returns the name of thread that is referred by object obj.

Let’s make a program where we will control main thread and also change name of main thread.

Program source code 2:

public class MainThreadDemo 
{
public static void main(String[] args) 
{
// Create a Thread object by calling currentThread() method of class Thread.
   Thread obj = Thread.currentThread();
   System.out.println("Current thread is " +obj);
   System.out.println("Name of current thread is " +obj.getName());
   
   obj.setName("New Thread"); // Changing name of main thread.
   System.out.println("Name of current thread after changing name is " +obj);
   System.out.println("Main thread existing");
  }
}
Output:
       Current thread is Thread[main,5,main]
       Name of current thread is main
       Name of current thread after changing name is Thread[New Thread,5,main]
       Main thread existing

In the preceding program, the name of main thread is changed by calling setName() method of Thread class and a new name of main thread is displayed. The new name of main thread is New Thread.

Use of Threads in Java


Threads can be used for multiple purposes. Some advantages of using threads are as follows:
1. Threads are mainly used in server-side programs where we need to handle multiple clients on network or internet simultaneously.

2. Another important use of threads is in creating games and animations. For example, threads can be used to show picture in motion. In many games, threads help to perform more than one task simultaneously.

For example, in fighter game, a fighter plane may be from left to right. A machine gun in fighter plane continuously shoots enemy by releasing bullets.

Here, two tasks are happening simultaneously. One thread is moving the fighter plane while another thread releasing bullets simultaneously.

3. Generally, threads can be used to perform more than one task simultaneously.

Final words
A program running on a single thread can cause problems when we want to perform two or more tasks simultaneously. For example, when you play online cricket game, you sometimes see such a situation where game does not show the updated score but still displays graphics properly.

Here, displaying graphics of game and updating scores are two different jobs that are to be handled at the same time. Therefore, it is important that the game programming must be able to handle these multiple tasks to make game fast.

To overcome these problems, Java supports multithreaded programming that enables a single program to perform multiple tasks simultaneously.

In multithreaded programming, each thread is assigned to perform a single task and executes independently. Multiple threads in a program share the same memory address space among themselves.

In the next tutorial, we will know multithreading in Java in more detail. Please share it for your friends on social networking sites.

Thanks for reading!!!