As any Java program comes under execution, first thread starts immediately, called the main thread. There are two importance’s of main thread as follows:
It is the parent of all the threads of the program and all other “child” threads will be spawned form it.
It must be the last thread to finish the execution of the program.
As your program start, the main thread is created automatically, under the control of Thread object. But, if you want the reference of the main thread then there is a static method curentThread() of Thread class, which returns the reference of thread in which it is called. Its general form is shown here:
static Thread currentThread( )
Example:
class MainThreadDemo
{
public static void main (String ar[] )
{
Thread t = Thread.currentThread();
System.out.println(“Current thread: ” + t);
t.setName(“Main Thread Demo”);
System.out.println(“New name of main Thread: ” + t);
try
{
for(int n=1;n<=10;i++)
{
System.out.print(i + ‘\t’);
Thread.sleep(500);
}
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}
Output:
Current thread: Thread[main,S,main]
New name of main Thread: Thread[Main Thread Demo,5,main]
1 2 3 4 5 6 7 8 9 10
Output is showing three line statement. In first statement within square brackets “[]” first value is the name of thread “main”, second is priority “5” and the last is the name of thread group “main”, the current (main) thread belongs to. Similarly in the second printed statement first value is name of the thread after modification “Main Thread Demo”, second is priority “5” and the last is thread group name “main”. The default created group by java is “main”. In the last it will print I to 10 and each digit after 0.5 second. In the above example setName() is used to change the name of the thread. You can get the name of the thread by calling getName(). Both of these methods are of Thread class. There prototype is given below:
final void setName(String threadName)
final String getName() ,
To give a pause to the thread sleep() method is used in the given example. The argument passed to sleep() method are in milliseconds. There are two versions of sleep() methods of Thread class as following:
static void sleep(long time_in_milliseconds) throws InterruptedException
static void sleep(long time_in_milliseconds, int additional_nanoseconds)
throws InterruptedException