Tuesday, June 16, 2015

What if we use run to call a thread's run method instead of start

What if we use run to call a thread's run method instead of start?
If we use run call, it will call the current thread, normally like any other normal method call with it's name and will display the current Thread name as main. This will also display the functionality of run method like any other method call.

While if we use start to call a thread, it creates a new thread and gives the created thread name which you passed while instantiating the Thread.

Programs depicting the above runVsStart Call:
package indoscopy;

public class StartVsRun{
          private static class MyThread extends Thread {
              public MyThread(String name) {
                  super(name);
              }
              @Override
              public void run() {
                  System.out.println(Thread.currentThread().getName());
              }
          }
          public static void main(String[] args) {
      
              MyThread myThread = new MyThread("myThread");
      
              myThread.run();
              myThread.start();
      
          }
      }

Output of the above program:
main
myThread

No comments:

Post a Comment