In Java programming, when a program begins the first thread that starts running is called main thread.
Other threads(child thread) can be spawned from this main thread.
When program terminates, the main thread must be the last thread in the program to end. When the main thread stops, the program stops running.
Main thread is created automatically, but it can be controlled by the program by using a Thread object.
By default name of main thread is “main”
By default Group name of main thread is “main”
By default priority of main thread is “5”.
Q.1 WAP to print the main thread and change the name of the main thread.
1 2 3 4 5 6 7 8 | public class MainTherad { public static void main(String a[]) { Thread obj = Thread.currentThread(); System.out.println("current = "+obj); obj.setName("NewMainThread"); System.out.println("after = "+obj); } } |
Output:
1 2 | current = Thread[main,5,main] after = Thread[NewMainThread,5,main] |
Q.2 WAP to print the 1 to 5 using thread and illustrate the use of sleep().
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class DemoTherad { public static void main(String a[]) { Thread obj = Thread.currentThread(); try { for (int i = 5; i > 0; i--) { System.out.println(i); obj.sleep(1000); } } catch (InterruptedException e) { System.out.println("Exception " + e.getMessage()); } } } |
Output:
1 2 3 4 5 | 5 4 3 2 1 |