Working with Main Thread : Simple

Main thread runs automatically when your program starts.
class MainThread
public static void main(String args[])
// Get current thread's object
Thread mainThread=Thread.currentThread();
// Get the name of the main thread
String oldName=mainThread.getName();
// Print the default name
System.out.println("My old name is "+oldName);
// Set a name to the main thread
mainThread.setName("My Main Thread");
// Print the new name
System.out.println("My new name is "+mainThread.getName());
// Start the loop
for(int i=5;i>=1;i--)
System.out.println(mainThread.getName()+": "+i);
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");
Output :

My old name is main
My new name is My Main Thread
My Main Thread: 5
My Main Thread: 4
My Main Thread: 3
My Main Thread: 2
My Main Thread: 1

Posted by at on

Tags: Multi Threading,