Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will happen if we directly call run method?

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(); ?
like image 446
DKS Avatar asked Dec 10 '13 18:12

DKS


2 Answers

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)

like image 55
rgettman Avatar answered Oct 02 '22 13:10

rgettman


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.

like image 31
sunil.tanwar Avatar answered Oct 02 '22 14:10

sunil.tanwar