Different between invoking run method as a thread i.e. – using start method and as a simple method.

Using Simple Method –

class UserThread extends Thread

{

      public UserThread(String name)

      {

            super(name);

      }

      public void run()

      {

            System.out.println("run() method is invoked from "+ getName() +" thread.");

            for(int i=1;i<=5;i++)

            {

                  System.out.println(i);

                  try

                  {

                        Thread.sleep(1000);

                  }

                  catch(Exception e)

                  {

                        System.out.println("run() is comleted.");

                  }

            }

      }

}

class ThreadTest

{

      public static void main(String[] arg)

      {

            Thread t=Thread.currentThread();

            System.out.println("main() method is invoked by "+ t.getName() +" thread.");

            UserThread th1=new UserThread("MyThread1");

            UserThread th2=new UserThread("MyThread2");

            System.out.println("Invoking run() _ _ _ ");

            th1.run();

            for(int i=5;i>=1;i--)

            {

                  System.out.println(i);

                  try

                  {

                        Thread.sleep(1000);

                  }

                  catch(Exception e)

                  {}

            }

      }

}

Invoking run method as a thread that is using simple method.PNG

Using start method –

class UserThread extends Thread

{

      public UserThread(String name)

      {

            super(name);

      }

      public void run()

      {

            System.out.println("run() method is invoked from "+ getName() +" thread.");

            for(int i=1;i<=5;i++)

            {

                  System.out.println(i);

                  try

                  {

                        Thread.sleep(1000);

                  }

                  catch(Exception e)

                  {

                        System.out.println("run() is comleted.");

                  }

            }

      }

}

class ThreadTest

{

      public static void main(String[] arg)

      {

            Thread t=Thread.currentThread();

            System.out.println("main() method is invoked by "+ t.getName() +" thread.");

            UserThread th1=new UserThread("MyThread1");

            UserThread th2=new UserThread("MyThread2");

            System.out.println("Invoking run() _ _ _ ");

            th1.start();

            th2.start();

            for(int i=5;i>=1;i--)

            {

                  System.out.println(i);

                  try

                  {

                        Thread.sleep(1000);

                  }

                  catch(Exception e)

                  {}

            }

      }

}

Invoking run method as a thread that is using start method.PNG

, , , , , , ,

Leave a Reply