Login    New User    Forgot Password    Help      

Thread Runnable

Java Tutorials

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by classThread. Being active simply means that a thread has been started and has not yet been stopped.

In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassingThread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

Example

// Creating Thread
//Implementing runnable  abstracts run() function from Runnable

class newtread implements Runnable
{
Thread t;
        // creates a second thread
        newtread()
        {
        // creates other thread
        t= new Thread(this , "New tread");
        System.out.println("Child Thread "+t);
        t.start();// Start the thread
        }

        // entry point for the second thread
        public void run()
        {
        try{
           for(int i=5;i>0;i--)
                {
                   System.out.print("Child Thread "+i+"  ");
                   Thread.sleep(500);
                   // use all thrre values and run again
                   //Thread.sleep(1000);
                   //Thread.sleep(2000);
                }
           }
       catch(InterruptedException e)
           {
           System.out.println("Child interruptedd ");
           }
        System.out.print("Exiting child thread  ");
        }

 

}
class tread2
{
public static void main(String args[])
{
new newtread();// create a new thread

Thread t= Thread.currentThread();
System.out.println();
//System.out.print("Current Thread "+t);

// renaming the thread
t.setName("Main Thread ");

int i;
try{
        for(i=1;i<=10;i++)
        {
        System.out.print(t);
        System.out.print("  ");
        Thread.sleep(1000);// sleep in milliseconds
        System.out.println(i);
        }
   }
   catch(InterruptedException e)
   {
    System.out.println("***");
   }
}
}

Output

Java Tutorials