The Wayback Machine - https://web.archive.org/web/20240627132826/https://www.geeksforgeeks.org/main-thread-java/
Open In App

Main thread in Java

Last Updated : 21 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins. 

There are certain properties associated with the main thread which are as follows:

  • It is the thread from which other “child” threads will be spawned.
  • Often, it must be the last thread to finish execution because it performs various shutdown actions

The flow diagram is as follows:

main thread in java

How to control Main thread

The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called. The default priority of Main thread is 5 and for all remaining user threads priority will be inherited from parent to child.

Example

Java




// Java program to control the Main Thread
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class 1
// Main class extending thread class
public class Test extends Thread {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Getting reference to Main thread
        Thread t = Thread.currentThread();
 
        // Getting name of Main thread
        System.out.println("Current thread: "
                           + t.getName());
 
        // Changing the name of Main thread
        t.setName("Geeks");
        System.out.println("After name change: "
                           + t.getName());
 
        // Getting priority of Main thread
        System.out.println("Main thread priority: "
                           + t.getPriority());
 
        // Setting priority of Main thread to MAX(10)
        t.setPriority(MAX_PRIORITY);
 
        // Print and display the main thread priority
        System.out.println("Main thread new priority: "
                           + t.getPriority());
 
        for (int i = 0; i < 5; i++) {
            System.out.println("Main thread");
        }
 
        // Main thread creating a child thread
        Thread ct = new Thread() {
            // run() method of a thread
            public void run()
            {
 
                for (int i = 0; i < 5; i++) {
                    System.out.println("Child thread");
                }
            }
        };
 
        // Getting priority of child thread
        // which will be inherited from Main thread
        // as it is created by Main thread
        System.out.println("Child thread priority: "
                           + ct.getPriority());
 
        // Setting priority of Main thread to MIN(1)
        ct.setPriority(MIN_PRIORITY);
 
        System.out.println("Child thread new priority: "
                           + ct.getPriority());
 
        // Starting child thread
        ct.start();
    }
}
 
// Class 2
// Helper class extending Thread class
// Child Thread class
class ChildThread extends Thread {
 
    @Override public void run()
    {
 
        for (int i = 0; i < 5; i++) {
 
            // Print statement whenever child thread is
            // called
            System.out.println("Child thread");
        }
    }
}


Output

Current thread: main
After name change: Geeks
Main thread priority: 5
Main thread new priority: 10
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread priority: 10
Child thread new priority: 1
Child thread
Child thread
Child thread
Child thread
Child thread

Now let us discuss the relationship between the main() method and the main thread in Java. For each program, a Main thread is created by JVM(Java Virtual Machine). The “Main” thread first verifies the existence of the main() method, and then it initializes the class. Note that from JDK 6, main() method is mandatory in a standalone java application.

Deadlocking with use of Main Thread(only single thread)

We can create a deadlock by just using the Main thread, i.e. by just using a single thread.

Example

Java




// Java program to demonstrate deadlock
// using Main thread
 
// Main class
public class GFG {
 
  // Main driver method
  public static void main(String[] args) {
 
    // Try block to check for exceptions
    try {
 
      // Print statement
      System.out.println("Entering into Deadlock");
 
      // Joining the current thread
      Thread.currentThread().join();
 
      // This statement will never execute
      System.out.println("This statement will never execute");
    }
 
    // Catch block to handle the exceptions
    catch (InterruptedException e) {
 
      // Display the exception along with line number
      // using printStackTrace() method
      e.printStackTrace();
    }
  }
}


Output: 

Image

Output explanation: 
The statement “Thread.currentThread().join()”, will tell Main thread to wait for this thread(i.e. wait for itself) to die. Thus Main thread wait for itself to die, which is nothing but a deadlock.

Related Article: Daemon Threads in Java.



Previous Article
Next Article

Similar Reads

Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version?
The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it. Deprecated methods are those that are no long
5 min read
How to Solve java.lang.IllegalStateException in Java main Thread?
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is not available then we will get RuntimeException sayi
5 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no
3 min read
Naming a thread and fetching name of current thread in Java
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. Methods: There are two ways by which we c
5 min read
Java main() Method - public static void main(String[] args)
Java's main() method is the starting point from where the JVM starts the execution of a Java program. JVM will not execute the code, if the program is missing the main method. Hence, it is one of the most important methods of Java, and having a proper understanding of it is very important. The Java compiler or JVM looks for the main method when it
7 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println(&quot;Hello&quot;); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
Java.lang.Thread Class in Java
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to p
8 min read
Daemon Thread in Java
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon t
4 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same shared memory This communication in multithreading ca
5 min read
Lock framework vs Thread synchronization in Java
Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackl
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg