10

I have a class "TestRunnable" which overrides run method by implementing Runnable. Running overridden run method, as follow :

TestRunnable nr = new TestRunnable();
Thread t = new Thread(nr);
t.setName("Fred");
t.start();
  • What if i directly call t.run();
  • What happen if we don't call t.start(); ?
Gray
  • 115,027
  • 24
  • 293
  • 354
DKS
  • 306
  • 1
  • 2
  • 16

3 Answers3

17

The run method is just another method. If you call it directly, then it will execute not in another thread, but in the current thread.

Here's my test TestRunnable:

class TestRunnable implements Runnable
{
   public void run()
   {
      System.out.println("TestRunnable in " + Thread.currentThread().getName());
   }
}

Output if only start is called:

TestRunnable in Fred

Output if only run is called:

TestRunnable in main

If start isn't called, then the Thread created will never run. The main thread will finish and the Thread will be garbage collected.

Output if neither is called: (nothing)

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

If you call start method then a separate thread will be allocated to execute the run method, means you achieve multi threading . But when you call run method directly then it becomes a normal method and main method itself will execute the run method , means no multi threading.

0

If run() method is called directly instead of start() method in Java code, run() method will be treated as a normal overridden method of the thread class (or runnable interface). This run method will be executed within the context of the current thread, not in a new thread.

Example

Let’s create a class and spawn two threads and cause some delay in the execution if they are real threads then there will be context switching – while one thread is not executing another thread will execute. When the start method is not called no new threads are created thus there won’t be any context switching and the execution will be sequential.

public class MyThreadClass extends Thread{
  @Override
  public void run(){
    System.out.println("In run method " + Thread.currentThread().getName());
    for(int i = 0; i < 5 ; i++){
      System.out.println("i - " + i);
      try {
        Thread.sleep(200);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
    
  public static void main(String[] args) {
    MyThreadClass mc1 = new MyThreadClass(“MyThread1”);
    MyThreadClass mc2 = new MyThreadClass();
    mc1.run();
    mc2.run();
  }
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Abhishek
  • 1
  • 2