Java-Create Threads by Runnable Interface

Create Threads by Runnable Interface

We can also create a thread by using the Runnable interface. This interface contains the declaration of only one method, namely the run( ) method. When we wish to create a thread by using the Runnable interface, we have to pass an instance of the class that implements this interface into the Thread constructor as its argument.

The following program defines a thread using the Runnable interface. The class Data implements the Runnable interface. An instance of Data is passed into the Thread constructor as its argument. Then, the start( ) method is invoked. When the JVM takes up the thread th1 for execution, the run( ) method in the Data class is executed. When the execution of the run( ) method is over, thread th1 completes its job.

Program

final


Program Source

class Data implements Runnable {
    
    public void run()
    {
        for(int i=10;i<=50;i+=10)
        {
            System.out.println("Data : "+i);
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Data da = new Data();
        Thread th1 = new Thread(da);
        th1.start();
    }
}

Leave a Comment