Monday, 13 July 2015

Java Creating a Thread

In the most general sense, you create a thread by instantiating an object of type Thread. Java identifies two ways in which this can be accomplished:

(i) You can implement the Runnable interface.

(ii) You can extend the Thread class, itself.

1. Implementing Runnable


The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run():

public void run()

Inside the run() method, you will define the code that constitutes the new thread. The run() can call other methods, use other classes and declare variables, just like the main thread.

The only difference is that run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class using one of the following constructors:

Thread(Runnable threadObj)

Thread(Runnable threadObj, String threadName)

Here threadObj is the object whose run method is called and threadName is the name of the new thread.

After the new thread is created, it will not start running until you call start() method. The start() method puts the thread in the ready queue (runnable state). Whenever the thread gets scheduled its execution will start from the run() method.

Example:

class X implements Runnable
      public void run()
     { 
          for(int i=1; i<=5; i++)
          { 
               System.out.println("Child Thread: " + I);
          }

          System.out.println("Exiting child thread");

      }

}

class RunnableTest
     public static void main(String args[])
     { 
         X runnable  = new X();

         Thread ct = new Thread(runnable);

          ct.start();

          System.out.println("main thread exiting");

      }

}

Output:

main thread exiting

Child Thread: 1

Child Thread: 2

Child Thread: 3

Child Thread: 4

Child Thread: 5

Exiting child thread

Example:

class NewThread implements Runnable
     Thread t;

      NewThread()
     { 
         t = new Thread(this, "Demo Thread");

         System.out.println("Child thread: " + t);

         t.start();

     }

     public void run()
     { 
           for(int i=5; i>0; i--)
           {
                 try
                 { 
                       System.out.println("Child Thread: " + I);
                 }
                 catch(InterruptedException e)
                { 
                     System.out.println(e);
                }
      }

      System.out.println("Exiting child thread”);

      Thread.sleep(500);

    }

}

class ThreadDemo
     public static void main(String args[])
    { 
          new NewThread();
          try
          { 
               for(int n=5; n>0; n--)
               {
                   System.out.println("Main Thread: " + n);
                   Thread.sleep(1000);
               }
           }
           catch(InterruptedException e)
           {
                System.out.println("main thread interrupted");
            }
           System.out.println("main thread exiting");
     }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread

Main Thread: 2

Main Thread: 1

main thread exiting

2. Extending Thread class

The second way to create a thread is to create a new class that extends Thread and then create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin the execution of the new thread.

Example:

public class NewThread extends Thread
     NewThread()
     { 
            super("Demo Thread");
            System.out.println("Child thread: " + this);
            start();
      }

      public void run()
      { 
          for(int i=5; i>0; i--)
          { 
              try
              {
                  System.out.println("Child Thread: " + I);
                  sleep(500);
              }
              catch(InterruptedException e)
              {

              }

          }
          System.out.println("Exiting child thread");
          System.out.println(e);
     }
}

class ExtendThread
        public static void main(String args[])
        { 
            new NewThread();
            try
            { 
                for(int n=5; n>0; n--)
                {
                     System.out.println("Main Thread: " + n);
                     Thread.sleep(1000);
                }
             }
            catch(InterruptedException e)
            {
                 System.out.println("main thread interrupted");
            }
            System.out.println("main thread exiting");
       }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread

Main Thread: 2

Main Thread: 1

main thread exiting

Note: If the thread is not assigned any name, it will be something like Thread-1, Thread-2, Thread-3 etc.

3. Choosing an Approach

The thread class defines several methods that can be overridden by a derived class. Out of these methods, the only one that must be overridden is run().

That is, of course, the same method required when you implement the Runnable interface. Many Java programmers feel that classes should be extended only when they are being enhanced or modified in some way.

So, if you will not be overriding any of Thread’s other methods, it is probably best simply to implement a Runnable interface.

No comments:

Post a Comment