Friday, 24 January 2014

THE MAIN THREAD

Java Exception in thread main Understanding with Examples

The 'main()' method in Java is referred to the thread that is running, whenever a Java program runs. It calls the main thread because it is the first thread that starts running when a program begins. Other threads can be spawned from this main thread. The main thread must be the last thread in the program to end. When the main thread stops, the program stops running.Main thread is created automatically, but it can be controlled by the program by using a Thread object. The Thread object will hold the reference of the main thread with the help of currentThread() method of the Thread class.


The general form is as shown below:

static Thread currentThread( )

Example:

class MainThread 
{
    public static void main(String args [] ) 
    {
        Thread t = Thread.currentThread ( );
        System.out.println ("Current Thread : " + t);
        System.out.println ("Name : " + t.getName ( ) );
        System.out.println (" ");
        t.setName ("New Thread");
        System.out.println ("After changing name");
        System.out.println ("Current Thread : " + t);
        System.out.println ("Name : " + t.getName ( ) );
        System.out.println (" ");
        System.out.println ("This thread prints first 10 numbers");
        try 
        {
            for (int i=1; i<=10;i++) 
            {
                System.out.print(i);
                System.out.print(" ");
                Thread.sleep(1000);
            }
        } 
        catch (InterruptedException e) 
        {
            System.out.println(e); 
        }
    }
}

Output:

Current Thread : Thread[main,5,main]
Name : main
After changing name
Current Thread : Thread[New Thread,5,main]
Name : New Thread
This thread prints first 10 numbers
1 2 3 4 5 6 7 8 9 10






No comments:

Post a Comment