Main Thread:
When we run a Java program then main thread begins running immediately. It is created automatically. The main thread is the first as well as last thread in a java program to end.
It is the main thread from which other child threads will be created.
Example:
// the main Thread.
public class MainThread {
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);
Thread.sleep(1000);
}
} 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
We can control main thread by using thread object. Thread object will hold the reference of the main thread with the help of currentThread() method of Thread class.
0 Comment(s)