Wednesday, 16 October 2013

The Concept of Main Thread:

       What is Main thread?

           In Java, when a program starts executing, a thread begins running immediately. This thread is called main thread of that program. When any program starts executing in Java then the main thread is the first thread that starts running and also, often it is the last thread to finish its execution.

       Why main thread is required?

1.      From the main thread other child threads are produced. 

2.      Main thread is responsible for various shutdown activities of any program in Java. So it is often the last thread to finish its execution.

            From the above discussion it is clear that, the main threads are created automatically when any program starts up in Java. In some situations it may be necessary for you to control the main thread. You can do this by obtaining a reference to it by calling currentThread() method which is a public static member of Thread class.

            The below example program shows how the main thread is controlled like any other thread in Java by getting a reference to it.

package blog.exception.mainThread;

public class DemoMainThread
   public static void main(String[] args)
                  Thread th=Thread.currentThread();
                  System.out.println("the Main thread i.e current thread "+th);
                  //get current thread name using getName()
                  System.out.println("current thread name before renaming is= "+th.getName());
                  //rename the current thread using setName()
                  th.setName("Demo Thread");
                  System.out.println("current thread name after renaming is="+th.getName());

the Main thread i.e current thread Thread[main,5,main]

current thread name before renaming is= main

current thread name after renaming is=Demo Thread

            In above program you can see a reference is obtained to the main thread by using currentThread() method defined by the Thread class. The name of the main thread is displayed by using getName() method and using setName() method the name main is changed to Demo Thread. Again after renaming, the new thread name is displayed by using setName() method.

Note: All the currentThread(), getName() and setName() methods used in the above example are defined by the Thread class.