VOOZH about

URL: https://www.geeksforgeeks.org/java/main-thread-java/

โ‡ฑ Main thread in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Main thread in Java

Last Updated : 3 Feb, 2026

When a Java program starts, the Java Virtual Machine (JVM) creates a thread automatically called the main thread. This thread executes the main() method and controls the overall execution flow of the program.

  • It is the parent thread from which all other user-defined threads are created.
  • The default name of the main thread is "main".
  • The default priority of the main thread is 5.
  • It usually finishes last as it may perform cleanup and shutdown tasks.
๐Ÿ‘ jvm

Create the Main Thread

The main thread is created automatically when the program starts. To control it, we must first obtain a reference to it using Thread.currentThread(). This method returns a reference to the currently executing 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

Explanation:

  • Thread.currentThread() returns the main thread.
  • getName() and setName() allow reading and changing the thread name.
  • getPriority() and setPriority() allow reading and changing the thread priority.
  • The main thread can create child threads, which by default inherit the main threadโ€™s priority.

Relationship Between main() Method and Main Thread

  • For every Java program, JVM creates the main thread first.
  • The main thread checks for the existence of the main() method, then initializes the class.
  • Since JDK 6, the main() method is mandatory for a standalone Java application.

Deadlock Using Main Thread

Even a single main thread can cause deadlock if it waits for itself.

Output: 

๐Ÿ‘ Image

Explanation:

  • Thread.currentThread().join() tells the main thread to wait for itself to die.
  • The thread waits indefinitely, causing a deadlock.
  • Any code after join() will never execute.
Comment
Article Tags: