Can we call run() method directly to start a new thread

No, you can not directly call run method to start a thread. You need to call start method to create a new thread.
If you call run method directly , it won't create a new thread and it will be in same stack as main.
Lets understand with the help of example:
package org.arpit.java2blog;
class CustomThread extends Thread {

 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }

}

public class StartThreadAgainMain {

 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.run();
  ct2.run();

 }

}


When you run above program , you will get below output:
Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4
Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4

As you can see when we are directly calling run method, it is not creating new threads.
If you use start instead of run in above example:
package org.arpit.java2blog;
class CustomThread extends Thread {

 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }

}

public class StartThreadAgainMain {

 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.start();
  ct2.start();

 }

}

When you run above program , you will get below output:
Thread is running :0
Thread is running :0
Thread is running :1
Thread is running :1
Thread is running :2
Thread is running :2
Thread is running :3
Thread is running :3
Thread is running :4
Thread is running :4
You can not directly call run method to create a thread, you need to call start method to create a new thread.

You can go through core java interview questions for beginners and experienced for more such questions. 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012