Main Thread in Java

In Java, the main thread is the thread that starts the execution of a Java program. Every Java program has a main method that serves as the entry point of the program. When the JVM starts up, it creates a thread to execute the main method, which is known as the main thread.

The main thread is a regular Java thread and can be manipulated like any other thread. However, there are some important differences between the main thread and other threads in a Java program:

  1. Lifetime: The main thread is the first thread to start and the last thread to finish in a Java program. It is created by the JVM when the program starts and exits when the main method finishes executing.

  2. Priority: The main thread has a default priority of 5, which is the normal priority level. However, the priority of the main thread can be changed using the setPriority() method.

  3. Name: The name of the main thread is "main", which can be retrieved using the getName() method.

  4. Daemon: The main thread is not a daemon thread, which means that it will keep the JVM running until it completes execution.

Here's an example that demonstrates the main thread in Java:

public class Main {
  public static void main(String[] args) {
    Thread mainThread = Thread.currentThread();
    System.out.println("Main thread name: " + mainThread.getName());
    System.out.println("Main thread priority: " + mainThread.getPriority());
    System.out.println(
      "Is main thread a daemon thread? " + mainThread.isDaemon()
    );
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Main thread exiting...");
  }
}

In this example, we retrieve the main thread using the currentThread() method and print some of its attributes, such as its name, priority, and whether it is a daemon thread. We then sleep the main thread for 5 seconds and print a message indicating that the main thread is exiting. This program will terminate when the main thread completes execution.