The Main Thread In Java

Hey Welcome To New Article today we will understand in depth about main thread in java :

We all know that execution of every java program start with main method :

public static void main(String[] args)

is main method in java itself is a Thread ?

Answer ,is NO..

No, the main method in Java itself is not a thread. However, the main method runs within a thread called the main thread.

Here’s the relationship between the two:

The main method is a special method that serves as the entry point for your Java program execution.
When you run a Java program, the Java Virtual Machine (JVM) automatically creates the main thread.
This main thread then starts executing the code within the main method.

So, the main method provides the instructions, and the main thread is responsible for carrying out those instructions.

Here are some additional points to consider:

The main thread is usually the first thread to start and the last one to terminate in a Java program.
You can create additional threads within your program to perform tasks concurrently. These additional threads are separate from the main thread.

The main thread is the fundamental building block of execution in any Java program. Let’s delve into its key aspects:

Automatic Creation:

  • When you start a Java program, the Java Virtual Machine (JVM) automatically creates the main thread. There’s no manual intervention required.

The Entry Point:

  • The main thread serves as the program’s entry point. It’s responsible for executing the main method, which is the starting point of your application’s logic.

Sequential Execution:

  • The main thread operates in a single-threaded manner. This means it executes the code within the main method line by line, one statement at a time.

Spawning Threads (Optional):

  • While the main thread itself runs sequentially, it has the capability to create additional threads if your program requires concurrent execution for specific tasks. These newly created threads are often called child threads.

Foreground Thread:

  • The main thread is a foreground thread. This implies that the program waits for the main thread to finish its execution before exiting. As long as the main thread is alive, the program continues to run.

Higher Priority (Usually):

  • In most cases, the main thread is assigned a higher priority than the threads you create within your program. This priority grants it preferential access to system resources like the CPU.

Accessing the Main Thread:

  • Although the main thread is created automatically, you can obtain a reference to it using the currentThread() method of the Thread class. This method returns a reference to the thread on which the current code is executing, which in this case, will be the main thread.

In summary, the main thread is the backbone of a Java program’s execution. It starts the program running, executes the main method, and can optionally spawn other threads if needed. Its foreground nature ensures the program keeps running until the main thread finishes its tasks.

package test;
public class SingleThread {
	public static void main(String[] args) throws InterruptedException {
		Thread myThread = Thread.currentThread();
		System.out.println("Name of current Thread is : ");
		System.out.println(myThread.getName());
		myThread.setName("SingleMainThread");
		System.out.println("Modified Name of current Thread is : ");
		System.out.println(myThread.getName());
		System.out.println("Calculate sum of first 100 number :");
		int num = 0;
		for (int i = 0; i <= 100; i++) {
			num++;
		}
		System.out.println("sum is : " + num);
	}
}

Here is basic examples of single-threaded programs in Java that showcase the power of a single thread in specific scenarios:

1.Simple Chat Application:

For a basic chat application within a single machine (not a network chat), a single thread can suffice:

The main thread maintains a chat history in memory.
Users take turns typing messages into the console.
The main thread reads the input from each user, adds it to the chat history, and displays the updated conversation on the screen.
While this approach wouldn’t work for a networked chat, it demonstrates how a single thread can manage basic turn-based interactions.

Here’s the code for a simple single-threaded chat application in Java:

package test;
import java.util.Scanner;
public class SimpleChat {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String chatHistory = "";
		// Welcome message
		System.out.println("Welcome to the Simple Chat!");
		while (true) {
			// Get input from User 1
			System.out.print("User 1: ");
			String message1 = scanner.nextLine();
			chatHistory += "User 1: " + message1 + "\n";

			// Get input from User 2
			System.out.print("User 2: ");
			String message2 = scanner.nextLine();
			chatHistory += "User 2: " + message2 + "\n";

			// Display updated chat history
			System.out.println("\nChat History:\n" + chatHistory);
		}
	}
}

Explanation:

1.Scanner and Chat History:

  • We create a Scanner object to read user input from the console.
  • A String variable chatHistory is used to store the conversation history.

2.Welcome Message:

  • The program prints a welcome message to the console.

3.Infinite Loop (Single Thread):

  • The while(true) loop ensures the chat continues until manually terminated.

4.User Input:

  • Inside the loop, we use Scanner to get messages from User 1 and User 2 sequentially.
  • Each message is stored in a separate variable (message1 and message2).

5.Update Chat History:

  • The received messages are appended to the chatHistory string with user labels.

6.Display Chat History:

  • The updated chatHistory is displayed on the console.

Running the Program:

  1. Compile the code and run it.
  2. Two users can then take turns typing messages and see the conversation history grow.

Limitations:

  • This is a single-threaded application, so only one user can type at a time. Typing simultaneously might lead to unexpected results.
  • It doesn’t handle exiting the chat gracefully. You’ll need to terminate the program manually (usually with Ctrl+C).

Note:

This code provides a basic example. It can be extended to include features like timestamps, user names, or the ability to exit the chat. However, keep in mind that for a real-time chat application with multiple users, a multi-threaded approach with networking capabilities would be necessary.

Single Thread Example In Java

contain single main thread , it will do execution in sequence , firstly it will print values of i and then it will print value of j as per method call , in a sequence :

package test;
public class SingleThreadDemo {
	public static void main(String[] args) {
		SingleThreadDemo st = new SingleThreadDemo();
		for (int i = 1; i < 5; i++) {
			System.out.println("i :" + i);
		}
		st.printJ();
	}
	public void printJ() {
		for (int j = 11; j < 15; j++) {
			System.out.println("j :" + j);
		}
	}
}

Output :

i :1
i :2
i :3
i :4
j :11
j :12
j :13
j :14

Happy Learning…

Leave a Reply

Your email address will not be published. Required fields are marked *