Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Thread in Java?
3.
Main Thread in Java
4.
Properties Associated with the Main Thread in Java
5.
Controlling the Main Thread in Java
5.1.
Using sleep() Method
5.2.
Java
5.3.
Using join() Method
5.4.
Java
5.5.
Using interrupt() Method
5.6.
Java
5.7.
Using Deadlock Scenario
5.8.
Java
6.
Frequently Asked Questions
6.1.
What is main thread group in Java?
6.2.
Which is the default thread in Java?
6.3.
How many main threads are there in Java?
6.4.
What are the responsibilities of the start() method?
7.
Conclusion
Last Updated: May 4, 2024
Medium

Main Thread in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java, well-known for its powerful multi-threading capabilities, is built around the concept of threads that run concurrently. The main thread is at the heart of any Java application.  This thread manages the application's lifecycle and organizes the program's entrance point. When a Java program starts up, the main thread executes the main method which serves as the program's starting point.

Main Thread in Java

In this article, we will discuss about main thread in Java and various methods to control it along with working code examples.

What is Thread in Java?

In Java, a thread is just a single independent path of execution of a group of statements. It is the flow of a task's execution from start to finish. When we write a group of statements in a program, JVM executes them one by one. In Java, this execution process is referred to as a thread. Every program has at least one thread running internally  and the JVM uses this thread to execute program statements.

A program that only has one flow of control is said to be single-threaded. A single-thread program runs commands sequentially and has a start, middle, and end. Additionally, we can create various execution threads within a program to carry out numerous activities concurrently.

Also see,  Eclipse ide for Java Developers,  Daemon Thread in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Main Thread in Java

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

The main thread is the last thread which gets executed in a program. When the main thread finishes the execution, the program terminates immediately. Whenever the Java program starts, the 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 the Thread class.

Properties Associated with the Main Thread in Java

  • Entry point: The main thread serves as the program's main() procedure  which serves as the program's entry point.
     
  • Foreground thread: Since the main thread is a foreground thread, the application will not exit until the  main thread completes its execution.
     
  • Single-thread processing: The main thread is a single-thread processing process, which means that it executes sequentially  one line at a time.
     
  • Higher priority: The main thread takes precedence over other threads launched by the program. It indicates that it has the  first pick of system resources such as the CPU.

Controlling the Main Thread in Java

Controlling the behavior of the main thread with the sleep(), join() and interrupt() methods is a common Java programming approach. These techniques allow you to add delays or synchronization points to the main thread's execution.

Using sleep() Method

The sleep() method which is part of the Thread class, allows developers to suspend a thread's execution for a set duration of time. It is very effective for mimicking time-consuming operations or causing delays. Here is a code example demonstrating how to use and syntax for Java's sleep() method:

Code:

  • Java

Java

public class temp {
public static void main(String[] args) {
   System.out.println("Start of Main Thread");
   try {
     // Sleep for 3 seconds or 3000 milliseconds
     Thread.sleep(3000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   System.out.println("Again Main thread is resumed after sleep.");
 }
}

Output:

Using sleep() Method

 

The main thread in the above program sleeps for 3 seconds (3000 milliseconds) by using the Thread.sleep() method. The InterruptedException is a checked exception that can arise when another thread interrupts a sleeping thread.

Using join() Method

The join() function in Java is also part of the Thread class and is used for synchronization. It enables one thread to await the conclusion of another. This is especially handy when programmers wish to verify that specific activities are performed before the main thread resumes processing. See the below example for a better understanding.

Code:

  • Java

Java

public class temp {

 public static void main(String[] args) throws InterruptedException {
   Thread studentThread = new Thread(() -> {
     System.out.println("student thread is starting.");
     try {
       Thread.sleep(3000);

     } catch (InterruptedException e) {
       e.printStackTrace();
     }
     System.out.println("student thread has completed.");

   });
   studentThread.start();
   // Wait for the student thread to complete
   studentThread.join();
   System.out.println("Main thread resumes after student thread.");
 }
}

Output:

Using join() Method

The main thread in the above code sample launches a student thread and then uses the join() method to wait for the worker thread to finish. This ensures that the worker thread completes before the main thread begins.

Also read, Java Ioexception

Using interrupt() Method

A thread's interrupt status is set by the cooperative interrupt() Java method, enabling it to respond politely to interruption requests. When used to implement thread cancellation and termination techniques in multi-threaded applications, it is important for ensuring effective resource management and responsiveness of the program. Head over to the below example for a better understanding:

Code:

  • Java

Java

import java.util.*;  
public class MainThreadInterrupt {
public static void main(String[] args) {
System.out.println("Main Thread is Started");

// create and start a new thread
Thread temporaryThread = new Thread(new OtherThread());
temporaryThread.start();

// interrupt the other thread after 2 seconds
try {
Thread.sleep(2000);
temporaryThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread has ended!");
}

private static class OtherThread implements Runnable {
public void run() {
System.out.println("Start of other thread");

// do some work in the other thread
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Performing some work");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread is interrupted");
}

System.out.println("End of other thread");
}
}
}

 

Output:

Using interrupt() Method

In this above illustration, a new thread is started by the main thread, which then interrupts it after two seconds. Until it is stopped, the new thread simulates work by printing a message every second.

Using Deadlock Scenario

When two or more threads are waiting for each other to release a received object, a deadlock develops. when two or more threads attempt to get locks on other threads' locked objects when they are each holding a lock on a different object. The given example will show the deadlock situation:

Code:

  • Java

Java

import java.util.*;  
public class Deadlock {
public static void main(String[] args) {
try {
System.out.println("You are going to enter into the deadlock");
// Joining the current thread
Thread.currentThread().join();
// This statement will never execute
System.out.println("This statement will never execute");
}
catch (InterruptedException ex) {
// Print the stack trace of the exception
ex.printStackTrace();
}
}
}

 

Output:

Using Deadlock Scenario

The statement "Thread.currentThread().join()" tells the main thread to wait for itself to finish, resulting in a deadlock in which the main thread waits eternally for itself to finish.

Must Read, even number program in java

Read more, how to run java program

Frequently Asked Questions

What is main thread group in Java?

In Java, all threads created by the JVM are included in the top-level thread group, which is represented by the main thread group. It acts as the application's parent group for every other thread group.

Which is the default thread in Java?

In Java, the default thread is the main thread. It is automatically created by the JVM to execute the main() method of the program. All Java applications start execution from the main thread.

How many main threads are there in Java?

There can only be one main thread per application in Java. When a program launches, the JVM automatically creates the main thread, which is in charge of carrying out the main() function

What are the responsibilities of the start() method?

The major goal of the start() method is to register the thread with the thread scheduler so that the thread scheduler can identify what the child thread should accomplish, when and how it will be scheduled.  The secondary responsibility is to call the threads' equivalent run() function.

Conclusion

Understanding the main thread in Java is essential for developing applications that are responsive, efficient, and robust. Developers can realize the full potential of multi-threading in Java by knowing its purpose, synchronization mechanisms, and best practices for thread management. In this article, we examined what a main thread in Java is, how to control it, and some frequently asked topics.

To better understand the topic, you can refer to hashCode() in JavaCreating a Thread, and Multithreading in Java.

For more information, refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!

Live masterclass