Controlling the main thread in Java

Java 8Object Oriented ProgrammingProgramming

A thread can be created by implementing the Runnable interface and overriding the run() method.

The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread. Also, it is the last thread to finish execution as various shut-down actions are performed by it.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      Thread t = Thread.currentThread();
      System.out.println("Main thread: " + t);
      t.setName("current");
      System.out.println("Current thread: " + t);
      try {
         for (int i = 1; i <= 5; i++) {
            System.out.println(i);
            Thread.sleep(10);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread is interrupted");
      }
      System.out.println("Exiting the Main thread");
   }
}

Output

Main thread: Thread[main,5,main]
Current thread: Thread[current,5,main]
1
2
3
4
5
Exiting the Main thread
raja
Published on 19-Feb-2019 06:06:44
Advertisements