Java Runnable example

Java Runnable

In this post, we will see Java Runnable example.
As you might know, there are two ways of creating threads in java.

  • Extending thread class
  • Implementing Runnable interface.

As you can extend only one class in java, it is not possible to extend any other class if a class extends thread class.You can also implement Runnable interface and then pass it Thread class constructor. As class can implement multiple interfaces in java, it is a good idea to create thread via implementing Runnable interface.

Java Runnable example

Create a class named SampleRunnable which will implement Runnable interface. When you implement Runnable interface, you need to provide an implementation for run method.

package org.arpit.java2blog;

public class SampleRunnable implements Runnable{

    public void run() {
        System.out.println("In run method");
    }
}

Create Main class named "JavaRunnableMain"

package org.arpit.java2blog;

public class JavaRunnableMain {

    public static void main(String[] args) {
        Runnable runnable=new SampleRunnable();
        // Pass Runnable to constructor of thread class
        Thread t=new Thread(runnable);
        t.start();
    }
}

When you run above program, you will get below output

In Run method

Java Anonymous Runnable example

You can also pass Runnable to Thread class by providing Anonymous Runnable implementation. You do not need to create separate class to implement run method.You can simply create Anonymous class and provide the implementation of run method.

package org.arpit.java2blog;

public class JavaAnoynomousRunnableMain {

    public static void main(String[] args) {
        Thread t=new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("In Run method");
            }
        });
        t.start();
    }
}

When you run above program, you will get below output

In Run method

Java 8 Runnable example

As Runnable is the functional interface, you can simply use the lambda expression to provide implementation of Runnable interface instead of creating Anonymous Runnable as above.

package org.arpit.java2blog;

public class Java8RunnableMain {

    public static void main(String[] args) {
        Thread t=new Thread(()->System.out.println("In Run method"));
        t.start();
    }
}

When you run above program, you will get below output

In Run method

That’s all about Java Runnable example.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.