You are here:   HomeJava ProgrammingMultithreadingisAlive() in Java Example
by Dinesh Thakur Category: Multithreading

Another way to create a thread in Java is to define a class that implements Runnable interface. The previous technique of creating threads by extending the Thread class does not workwhen you want a class that extends another class and can also be run as a thread. This is becauseJava supports only single inheritance i.e. does not allow a class to extend more than one class. So insuch a case implement the Runnable interface. The Runnable interface declares only one method run () that contains the code that will be executed when the thread is started. Therefore, if youdefine a class that implements the Runnable interface then it must implement the run () method.

The Runnable interface is commonly used when you add multithreading support to applets for animation or other purposes. It is required because Applet class already extends java.applet.Applet class and it not possible to extend the Thread class.

Now let us consider a class MyThread that implements Runnable interface.

class MyThread implements Runnable

{
      private int threadId;
      private int delay;
      MyThread(int id,int d)
      {
        threadId=id;
        delay = d;//time for which thread sleeps
      }
      public void run()
      {
         for(int i=0;i<5;i++)
            {
                 System.out.println("Thread " + threadId +" is running");
                 try
                 {
                     Thread.sleep(delay);
                 }
                 catch(InterruptedException e)
                 {
                      e.printStackTrace();
                 }
            }
                      System.out.println("Thread " + threadId +" is Finished");
        }
}
      public class RunnableThread
      {
            public static void main(String[] args)
          {
                  System.out.println("Main thread starts");
                  MyThread r1 = new MyThread(1,500);
                  MyThread r2 = new MyThread(2,300);
                  MyThread r3 = new MyThread(3,600);
                  Thread t1 = new Thread(r1);
                  Thread t2 = new Thread(r2);
                  Thread t3 = new Thread(r3);
                  t1.start();
                  t2.start();
                  t3.start();
                  System.out.println("Main thread is finished");
          }
      }

Creating Thread Using Runnable Interface in Java Example