Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, 22 November 2016

What is Main Thread In Java ?

Previously we have discussed about
www.javaidentifiers.com
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 program begins.

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 a public static member of Thread. 
Its general form is shown here:
static Thread currentThread( )

The current thread (the main thread, in this case) is obtained by calling currentThread( ) method,and this reference is stored in the local variable th as show in example.

By default, the name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs.

A thread group is a data structure that controls the state of a collection of threads as a whole.This time, the new name of the thread is displayed.

You can set the name of a thread by using setName( ) method, You can obtain the name of a thread by calling getName( ) method.These methods are members of the Thread class.

Example of Main Thread:

public class MainThreadExample {

public static void main(String[] args) {
Thread th = Thread.currentThread();
System.out.println("CURRENT THREAD NAME : "+th);
//Changing the Thread Name
th.setName("New Thread Name");
System.out.println("THREAD NAME AFTER CHANGE : "+th);
try {
for(int i=10;i>0;i--){
System.out.println(i);
Thread.sleep(200);
}
} catch (Exception e) {
System.out.println("EXCEPTION : "+e);
}
}

}
Program Output:

CURRENT THREAD NAME : Thread[main,5,main]
THREAD NAME AFTER CHANGE : Thread[New Thread Name,5,main]
10
9
8
7
6
5
4
3
2
1

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment