Java-Get Main Thread Reference

Get Main Thread Reference

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread.

In the following program, a reference to the current thread(the main thread, in this case) is obtained by calling currentThread( ), and this reference is stored in the local variable mth. Next, the program displays the name of thread. The program then calls setName( ) to change the internal name of the thread. Name of the thread is then redisplayed. Next, the program then calls stop( ) to stop the thread. Note the Exiting ThreadMain statement not executed, because thread stopped.


fgf final

Program Source

public class Javaapp {
    public static void main(String[] args) {
        Thread mth = Thread.currentThread();
        System.out.println("Main Thraed Name : "+mth.getName());
        System.out.println("Main Thraed Name : "+mth.getName());
        System.out.println("Exiting ThreadMain");

One thought on “Java-Get Main Thread Reference

Leave a Comment