Java2all.com  

The Main Thread





Share This Topic -

The Main Thread:

When our simple program starts one single thread begins running immediately.
 
This is called our single main thread.

The main thread create automatically when program is started.

It is very important thread because of two reason.
 
1.) From the main thread other child thread will be created.
2.) Main thread is all most everytime stop running lastly because it has to remove or shutdown few resources as well as few action.
 
Now the question is how can we control our main thread?
 
Actually by calling the method currentThread() of Thread class we can control our main thread.
 
EX:
 public class Main_Thread 
{
	public static void main(String args[]) 
	{
		Thread t = Thread.currentThread();
		System.out.println("Current thread: " + t);
		
		// change the name of the thread
		t.setName("My Thread");
		System.out.println("After name change: " + t);
		try 
		{
			for(int n = 5; n > 0; n--) 
			{
				System.out.println(n);	//print number with interval of 1 sec.
				Thread.sleep(1000);		//Thread is going to sleep for 1 sec.
			}
		} 
		catch (InterruptedException e) 
		{
			System.out.println("Main thread interrupted");
		}
	}
}

Output:
 
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
 
Here first of all we give reference of our current main single thread to t by thread object and currentThread() method.
 
The number 5 to 1 will be print at interval of 1 second due to sleep method.
 
Thread will go to sleep for 1000 ms. due to sleep method

Now we will see the lifecycle of thread.