Table of Contents
Introduction
Multithreading is a JAVA concept where several parts of a program can run concurrently. These individual parts are called threads. Each thread dictates a separate path of execution. When you start up a Java program or application, there is always one thread that immediately starts up and is independent of the other threads. This is called the main thread of your program. As this thread gets executed before the program begins, is the main thread.
Properties of the Main Thread
- As the Main Thread is the first thread that gets executed before the program begins, all subsequent threads or child threads are spawned from here. Therefore, the main thread might be put to waiting status as it gathers information after the execution of the child threads.
- Although it is not always the case, for majority of programs and applications, the main thread is often the last thread to be rendered dead. Computationally, as the main thread directs the flow of the program, to shut it down would mean shutting down the program as a whole.
How to Control the Main Thread
A reference to the thread is needed to control it. To control the main thread, we can refer to it by using the method currentThread() which is present in the Thread class. The following is an example to illustrate it:
public class Test extends Thread { public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t.getName()); t.setName("Demo_Main"); System.out.println("After name change: " + t.getName()); System.out.println("Main thread priority: "+ t.getPriority()); t.setPriority(MAX_PRIORITY); System.out.println("Main thread new priority: "+ t.getPriority()); for (int i = 0; i < 5; i++) { System.out.println("Main thread"); } // Creating main thread ChildThread ct = new ChildThread(); System.out.println("Child thread priority: "+ ct.getPriority()); ct.setPriority(MIN_PRIORITY); System.out.println("Child thread new priority: "+ ct.getPriority()); ct.start(); } } class ChildThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("Child thread"); } } }
OUTPUT
Current thread: main
After name change: Demo_Main
Main thread priority: 5
Main thread new priority: 10
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread priority: 10
Child thread new priority: 1
Child thread
Child thread
Child thread
Child thread
Child thread
0 Comments