The main thread

A very important fact is that when a Java program starts, it has just one thread – the main() method. We can interact with the main thread in various ways, such as getting or setting its name, pausing it, and more. Here is an example:

MainThread.java

public class MainThread {

public static void main(String[] args) {

Thread thread = Thread.currentThread();
  System.out.println("Main thread's actual name is: "+ thread.getName());
thread.setName("The Main Thread");
  System.out.println("Main thread's name is now: " + thread.getName());
  }

}

Output

C:\thread>java MainThread
Main thread's actual name is: main
Main thread's name is now: The Main Thread
 
Explanation:-

The currentThread() method of the Thread class gets the current thread; if we are executing in the main method, currentThread() gets the main thread. We can get the name of a thread by using the getName() method, whereas we can set a thread’s name with the setName() method.

Sometimes, we want to pause a thread’s execution, and we can do that with the sleep() method of the Thread class. We pass this method the amount of time to pause as a parameter, in milliseconds (a millisecond is one-thousand of a second), and the thread will wait that amount of time before continuing. Here’s an example in which we print out a message, pausing for 1000 milliseconds (1 second) between words:

Pause.java

public class Pause {

public static void main(String[] args) {

   try {
     System.out.println("Core");
     Thread.sleep(1000);
      System.out.println("Java");
      Thread.sleep(1000);
      System.out.println("Course");
      Thread.sleep(1000);
    }
    catch (InterruptedException e) { }
  }

}

Output

C:\thread>java Pause
Core
Java
Course

 

When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being Runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

An example of an anonymous class below shows how to create a thread and start it:

Test.java

class Test {

public static void main(String a[]) {

    ( new Thread() {

          public void run() {
              for(int i=1;i<=5;i++) System.out.println("Hello World!");
          }

    } ).start();

}

}

 

Output

C:\thread>java Test
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!