We can call run() method if we want but then it would behave just like a normal method and we would not be able to take the advantage of multithreading. When the run method gets called though start() method then a new separate thread is being allocated to the execution of run method, so if more than one thread calls start() method that means their run method is being executed by separate threads (these threads run simultaneously).
On the other hand if the run() method of these threads are being called directly then the execution of all of them is being handled by the same current thread and no multithreading will take place, hence the output would reflect the sequential execution of threads in the specified order. Did it confuse you? Lets have a look at the below code to understand this situation.
Calling run() method
public class RunMethodExample implements Runnable{ public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); }catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.run(); th2.run(); } }
Output:
1 2 3 1 2 3
As you can observe in the output that multithreading didn’t place here, it because both the run methods are being handled by the current thread. that treated them like normal methods and had them executed in the specified order rather then having them executed simultaneously. Thread scheduler didn’t play any role here.
Calling start() method
Multithreading takes place and the output reflects simultaneous execution of threads.
public class RunMethodExample2 { public void run(){ for(int i=1;i<=3;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ ie.printStackTrace(); } System.out.println(i); } } public static void main(String args[]){ Thread th1 = new Thread(new RunMethodExample(), "th1"); Thread th2 = new Thread(new RunMethodExample(), "th2"); th1.start(); th2.start(); } }
Output:
1 1 2 2 3 3
As you can see the output reflects the simultaneous execution of threads.
Albert Nguyen says
Hello ,
Could you please explain to me:
“When the run method gets called though start() method then a new separate thread is being allocated to the execution of run method”
Thank you for your explanation indeed,
Albert