What will happen if we directly call the run() method in Java?

JavaObject Oriented ProgrammingProgramming

A direct call of a Thread object's run() method does not start a separate thread and it can be executed within the current thread. To execute Runnable.run from within a separate thread, do one of the following

  • Construct a thread using the Runnable object and call start() method on the Thread.
  • Define a subclass of a Thread object and override the definition of its run() method. Then construct an instance of this subclass and call start() method on that instance directly.

Example

public class ThreadRunMethodTest {
   public static void main(String args[]) {
      MyThread runnable = new MyThread();
      runnable.run(); // Call to run() method does not start a separate thread
      System.out.println("Main Thread");
   }
}
class MyThread extends Thread {
   public void run() {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         System.out.println("Child Thread interrupted.");
      }
      System.out.println("Child Thread");
   }
}

In the above example, the main thread, ThreadRunMethodTest, calls the child thread, MyThread, using the run() method. This causes the child thread to run to completion before the rest of the main thread is executed, so that "Child Thread" is printed before "Main Thread".

Output

Child Thread
Main Thread
raja
Published on 23-Aug-2019 11:30:44
Advertisements