The main thread in java

Most of us already know about the main thread in java. But there are still some doubts about the main thread like why we use it? How JVM invokes it? What is the advantage of the main thread in java?

Here is the table content of the article will we will cover this topic.
1. What is the main thread in java?
2. Important points about the main thread?
i) Automatically created by JVM
ii) Produce other threads
iii) Must be the last thread to finish execution
iv) To control the main thread
v) Creating a deadlock by the main thread

In multithreading, a program can have multiple threads. But each program must contain at least one thread whether we are creating any thread or not. The JVM provides a default thread in each program. A program can’t run without a thread, so it requires at least one thread, and that thread is known as the main thread.

What is the main thread in java?

As we know every java program has a main method. The main method is the entry point to execute the program. So, when the JVM starts the execution of a program, it creates a thread to run it and that thread is known as the main thread.
If you are creating a simple program to print “Hello world” it means JVM will create the main thread to execute it. You must saw if you try to run a Java program with compilation errors the JVM shows the error in the main thread.

class ExampleOfThreadCreation
{  
   public static void main(String args[])
   {
	   a;
	   System.out.println("Hello world");
   }  
}  

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problems:     Syntax error, insert “VariableDeclarators” to complete LocalVariableDeclaration a cannot be resolved at ExampleOfThreadCreation.main(ExampleOfThreadCreation.java:5)

The JVM automatically creates the main thread but we can verify it and also control this thread.  To control the main thread, we need to get the reference of the thread. We can get the refence of the main thread by calling the method currentThread( ), which is a public static member of Thread. This method will return the reference of the thread in which it is called. So when we call it in the main thread it will return the reference of the main thread. After that, you can control it just like any other thread. Let’s try it with an example

class ExampleOfThreadCreation
{  
   public static void main(String args[])
   {
	   Thread obj = Thread.currentThread();
	   System.out.println("Name of thread :" +obj.getName());
	   System.out.println("Priority of thread :" +obj.getPriority());
	   // We can set the Name of main thread
	   obj.setName("Main thread");
	   System.out.println("Name of thread :" +obj.getName());
	   System.out.println("Hello world");
   }  
}  

Output: Name of thread :main
Priority of thread :5
Name of thread :Main thread
Hello world

In the above example, we are getting the object by use of currentThread() method. We are getting the properties of the main thread and also changing the name of the main thread.  

Important points about the main thread

1. Automatically created by JVM

The JVM creates the main thread automatically when it starts the execution of the program. Whether you create any thread or not, the main thread exists in the program. The JVM allocates a stack to each thread, that is used for storing runtime data. When JVM starts the execution from the main method it creates a stack for the main thread and stores the data in the particular stack.
You can read it in detail.

All the method calls store in the stack and each entry is known as a stack frame. A stack can have several stack frames that totally depend upon the stack size. If a thread tries to store more items on the stack than the stack size allows, the thread will throw a stack overflow error.
Let us see how the main thread is created by JVM and how does it work.

public class JavaGoal
{
    public static void main(String args[]) 
    {
        System.out.println("Main method");
        JavaGoal obj = new JavaGoal();
        obj.firstMethod();
        obj.secondMethod();
    }
    
    public void firstMethod()
    {
        System.out.println("First Method");
    }
    
    public void secondMethod()
    {
        System.out.println("Second Method");
    }
}

Output: Main method
First Method
Second Method

2. Produce other threads

It is the thread from which other child threads will be spawned. Because it is already created by JVM so whenever we will create any thread it is considered as a child of the main thread. As we know default priority of main thread is 5 so all the child thread inherits its priority also.

main thread in java

3. Must be the last thread to finish execution

The main thread must be the last thread to finish the execution because it performs various shutdown options. When the main thread stops, the program stops running.

4. To control the main thread in java

When our program is started then the main thread is created automatically. You can control the main thread by reference of main thread. You can obtain the reference by calling the method currentThread( ) which is present in Thread class.

public class MainThread extends Thread 
{
   public static void main(String[] args) 
   { 
 	// getting reference of Main thread 
	Thread mainThread = Thread.currentThread(); 
		
	// getting name of Main thread 
	System.out.println("The name Current thread = " + mainThread.getName()); 
		
	// changing the name of Main thread 
	mainThread.setName("JAVAGOAL"); 
	System.out.println("After name change of current thread = " + mainThread.getName()); 
			
	// getting priority of Main thread 
	System.out.println("Main thread priority = "+ mainThread.getPriority()); 
			
	// setting priority of Main thread. Priority can be set MIN(1) to MAX(10) 
	mainThread.setPriority(MAX_PRIORITY); 
		
	// Getting the priority after setting up 
	System.out.println("Main thread new priority = "+ mainThread.getPriority()); 
			
	// Main thread creating a child thread 
	ChildThread childThread = new ChildThread(); 
				
	// starting child thread 
	childThread.start(); 
    } 
} 

// Child Thread class 
class ChildThread extends Thread 
{ 
   @Override
   public void run() 
   { 
	// It returns child thread because after calling of childThread.start() 
        //current thread is child thread.
	ChildThread childThread = (ChildThread) Thread.currentThread();
	// getting name of Main thread 
	System.out.println("The name child thread = " + childThread.getName()); 
					
	// changing the name of child thread 
	childThread.setName("ChildThreadOfJAVAGOAL"); 
	System.out.println("After name change of child thread = " + childThread.getName()); 
						
	// getting priority of child thread 
	System.out.println("Child thread priority = "+ childThread.getPriority()); 
					
	// setting priority of child thread.
	childThread.setPriority(MIN_PRIORITY); 
		
	// Getting the priority after setting up 
	System.out.println("Main thread new priority = "+ childThread.getPriority()); 
			
	System.out.println("This is child thread");
      } 
} 

Output: The name Current thread = main
After name change of current thread = JAVAGOAL
Main thread priority = 5
Main thread new priority = 10
The name child thread = Thread-0
After name change of child thread = ChildThreadOfJAVAGOAL
Child thread priority = 10
Main thread new priority = 1
This is child thread

In the above example, we are getting the main thread by calling Thread.currentThread().  We can set the name and priority of the main thread. We are creating another thread from the main thread that child thread.

5. Creating a deadlock by the main thread in java

As you know main thread should be terminated at last when a number of threads are running. If you call join method by the main thread the program goes to deadlock. For more details, you should read the join method.

public class MainThreadDeadlock 
{
  public static void main(String[] args) 
  {
     try 
     {
	Thread.currentThread().join();
        // the following statement will never execute because main thread join itself 
        System.out.println("This statement will never execute"); 
     }
     catch (InterruptedException e) 
     {
	e.printStackTrace();
     }
  }
}

1 thought on “The main thread in java”

Leave a Comment