A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Define a thread by implementing Runnable Interface

Defining a thread by implementing Runnable Interface

Defining a thread by implementing Runnable Interface

Runnable interface is present in the java.lang package and it contains only one method run( ).
Now, a question arise i.e.
Why a thread implements Runnable Interface, because it can be used as extending Thread class.
My Answer is, because when we use the extending method in multithreading we can't take full benefits of Inheritance as if required a programmer to extend some another class or need to use another method that is not available in Thread Class in java. 
Hence, it is more powerful and beneficial if you are using implementing interface methods.
Example:


class myRunnable implements Runnable
{
    public void run()
    {
        for(int i=0; i<10; i++)
        {
            System.out.println("child thread");
        }
    }
}

class ThreadDemoImpliment
{
    public static void main(String [] args)
    {
        myRunnable R = new myRunnable();
        Thread t = new Thread(R);
        t.start();
        for(int i = 0; i<10; i++)
        {
            System.out.println("Main thread");
        }
    }

}

Here, myRunnable class implements Runnable interface and it contains only one method run, in which a for loop is written as the job of the thread. Another class ThreadDemoImpliment is written.

Now, an object R is being created in the main method. Similarly, a thread object t is created and an argument R is passing from this. Further t.start( ) method is called to start thread. In the last another for loop is written, which is called by  main thread of the main method.

OutPut:



LEARN TUTORIALS

.

.