Showing posts with label java main thread. Show all posts
Showing posts with label java main thread. Show all posts

Monday, 13 July 2015

Java The main thread

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 programs begins.

The main thread is the thread from which other “child” threads are created.

Although 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 public static member of Thread class. This method returns a reference to the thread in which it is called.

Once you have a reference to the main method, you can control it just like any other thread.

Example: The following example demonstrates how we can acquire reference of main thread and then access its properties using methods of Thread class.

class CurrentThreadDemo
     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("Priority: " + t.getPriority());

            t.setName("My Thread");

            t.setPriority(10);

            System.out.println("After name and priority change : " + t);

             System.out.println("New Name: " + t.getName());

             System.out.println("New Priority: " + t.getPriority());

             try
             { 
                    for(int n=5; n>0; n--)
                    { 
                         System.out.println(n);
                    }
             }
             catch(InterruptedException e)
             { 
                  System.out.println("main thread interrupted");
             }

             Thread.sleep(1000);
     }

}

Output:

Current thread: Thread[main,5,main]

Name: main

Priority: 5

After name and priority change : Thread[My Thread,10,main]

New Name: My Thread

New Priority: 10

5

4

3

2

1

The sleep() method in Thread might throw an InterruptedException, which is a checked exception. This would happen if some other thread wanted to interrupt this sleeping one.

Notice the output produced when t (thread reference) is used as an argument to println(). This displays in order: the name of the thread, its priority, and the name of its group. Its priority is 5, which is the default value, and main is also the name of the group of thread to which this thread belongs.

A thread group is a data structure that controls the state of a collection of threads as a whole.