Main Thread in Java

Java is one of the first programming language to provide built-in support for multi-threading. In fact when a Java program starts one thread starts running immediately that thread is known as main thread in Java.

If you ever tried to run a Java program with compilation errors you would have seen the mentioning of main thread. Here is a simple Java program that tries to call the non-existent getValue() method.

As you can see in the error when the program is executed, main thread starts running and that has encountered a compilation problem.

Main Thread

Main thread in Java is important as your Java program will start running on this thread.

Additional threads spawned in your program will inherit some of the properties from the main thread like thread priority, threads are created as non-daemon threads as main thread is non-daemon thread.

The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died. If you have spawned other threads in your program that are non-daemon then main thread may terminate before those threads.

Let’s see a Java example to clarify these statements.

Main thread Java example

In the program we’ll display the name of the thread in the main method and using isAlive() method it is also verified whether thread is still alive or terminated.

Three more threads are also spawned, in order to keep checking on the status of the main thread its reference is sent to the class that implements Runnable.

Output

As you can see from the output main thread is terminated while other threads are still executing.

That’s all for the topic Main Thread in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: Daemon Thread in Java - KnpCode

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.