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.

Create Main class named "JavaRunnableMain"

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.

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.

When you run above program, you will get below output

In Run method

That’s all about Java Runnable example.

Was this post helpful?

Leave a Reply

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