java tutorial - What if we call run() method directly - java programming - learn java - java basics - java for beginners



What if we call run method directly

Learn Java - Java tutorial - What if we call run method directly - Java examples - Java programs

What is the run method?

  • The method is a set of code which referred to by name and it can be called (invoked) at any point in a program just by utilizing the method's name.
  • Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.

What if we call run() method directly instead start() method?

  • To invok run() method on or after the main thread, then the method go onto the present call stack sooner than at the starting of a new call stack.

Sample Code

public class CallRun extends Thread{
public void run(){
System.out.println("Welcome to Wikitechy Tutorials!!!");
}
public static void main(String args[]){
CallRun time1=new CallRun();
time1.run();//fine, but does not start a separate call stack
}
}
click below button to copy the code. By - java tutorial - team

Output

Welcome to Wikitechy Tutorials!!!

Sample Code

public class CallRun extends Thread{  
 public void run(){  
  for(int i=3;i<6;i++){  
    try{Thread.sleep(100);}catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  CallRun t1=new CallRun();  
  CallRun t2=new CallRun();
  CallRun t3=new CallRun();
   
  t1.run();  
  t2.run();  
  t3.run();  
 }  
}  
click below button to copy the code. By - java tutorial - team

Output

3
4
5
3
4
5
3
4
5

Related Searches to What if we call run() method directly