Multithreading by Extending Thread Class

  • 1
Multi-threading is a topic, that I found most difficult to understand. First thing that needs to be understood is the distinction between a Thread and a Program. Thread is the smallest unit of execution. A program may contain more than one thread that executes concurrently. Let me tell you that saying concurrent execution is not correct, a computer processor can execute only one process at a time (single core processors), and if a process involves more than one Thread, only one Thread, would execute at a time, when a Thread gets paused, then and then only, any other Thread can start executing. If you ask what exactly is the advantage of multi-threading, then the advantage of multi-threading is that you can assign different tasks to Threads, for example, As in Android, Image Retrieval from database is time consuming and processor intensive task, so it is preferred to implement image retrieval mechanism on a separate thread.
Java provides two ways of creating multi-threaded programs, first one, here is by extending Thread class (which is one we are going to demonstrate here), and second method is by implementing Runnable interface. Here is the code for it.

package MultiThreadingIllustration;

class ExtendThread extends Thread
{
 ExtendThread()
 {
  super("Second");
  System.out.println("Second Thread" + this);
  start();
 }
 
 public void run()
 {
  try
  {
   for(int i=0;i<=5;i++)
   {
    System.out.println("Second Thread " + i);
    Thread.sleep(500);
   }
  }
  catch(InterruptedException e)
  {
   System.out.println("Interrupted Exception Caught ");
  }
  System.out.println("Second Thread Exited");
 }
}
class ExtendThreadDemo
{
 public static void main(String...args)
 {
  ExtendThread et = new ExtendThread();
  
  try
  {
   for(int i=0;i<=5;i++)
   {
    System.out.println("Main Thread " + i);
    Thread.sleep(1000);
   }
  }
  catch(InterruptedException e)
  {
   System.out.println("InterruptedException Caught ");
  }
  System.out.println("Main Thread Exited");
 }
}

1 comment:

  1. Good work. Keep it up. At the end of the day, self exploration and discovery is your best mentor.

    all the best..

    ReplyDelete