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:
When you run above program , you will get below output:
As you can see when we are directly calling run method, it is not creating new threads.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
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 |
If you use start instead of run in above example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.