The main thread in java

When a java program starts up one thread begins running immediately .This usually called the main Thread of your program ,Because it is the one that is executed when your program begins .The main thread is important for two reason

1) It is the thread from which other child threads will be spawned
2) Often it must be the last thread to finish execution because it performs various shutdown actions

 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 members of thread .its general form is shown here
static Thread currentThread()


Program : CurrentThread.java

class CurrentThread
{
public static void main(String arg[])
    {
     Thread t=Thread.currentThread();
System.out.println("Current Thread : "+t);
t.setName("my Thread");
System.out.println("After name change :"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Man Thread interrupted ");
}
}
}



In this program a reference to the current thread is  obtained by calling currentThread() and this  reference is stored in the local variable .next ,the program  displays information about  the thread .The program then calls setName() to change the internal name of the thread .Information about the thread  is then redisplayed .Next a loops counts down from five pausing one second between each line .The pause is accomplished by the sleep() method .The argument to sleep() specifies the delay period in milliseconds .Notice the try/catch block around  this loop.The sleep() method in thread might throw an InterruptedException .This would happen if some other thread wanted to interrupt this sleeping one .This example just prints a message .if its gets interrupted .In a real program .You would need to handle this differently .Here is the output generated by this program



Output

Current thread :Thread[main,5,main]
after name change: Thread[my Thread ,5,main]
5
4
3
5

The main thread  in java
1

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org